javascript - 调用方法比从内存中检索内容更快

标签 javascript html dom

所以这是我的问题:为什么调用方法比从内存中检索某些东西更快?

注意,当在 DOM 元素上指定 id 属性时,用户代理会自动在其全局范围内附加该元素的引用。

既然用户代理已经引用了所有指定了 id 属性的元素,为什么我需要使用 document.getElementById("")?

在应用程序中,我会:

//Retrieving the value, I could possibly write this two way.
<script>
var fromGlobalScope = myElement.value;
var documentGetById = document.getElementById("myElement").value;
</script>


<input id="myElement" value="someValue" />

做了一些研究,所有主流浏览器都支持它,但它们可能有一些不支持的浏览器,这会崩溃。

但是,我可以简单地写:

<script>

//See if the element is on the global scope.
var fromGlobalScope = myElement ||document.getElementById("myElement");

</script>

我相信模式正确,我可以自动引用所有具有 id 属性的元素。我不必调用 document.getElementById();

使用常驻属性并且我不必遍历 DOM,我认为会有很好的性能优势。

我创建了一个 jsPerf 来查看好处:enter link description here

令我惊讶的是,使用 document.getElementById() 速度更快?

所以这是我的问题:为什么调用方法比从内存中检索某些东西更快?

使用 document.getElementById,我将调用一个可能遍历也可能不遍历 DOM 的方法。至少,我会为该值调用一个地址。

具有全局范围内的属性,该属性应该可以快速使用,因为它被放置在某个内存位置。

我在下面包含了 jsPerf 结果: enter image description here

我用另一种想法创建了另一个 jsPerf: explicitly setting a property on the window object

但是,我仍然相信了解为什么可以帮助了解正在发挥作用的机制,这可能会产生一些有用的结果。

最佳答案

来自 HTML5 spec

5.2.4 Named access on the Window object

The Window interface supports named properties. The supported property names at any moment consist of the following, in tree order, ignoring later duplicates:

  • the browsing context name of any child browsing context of the active document whose name is not the empty string,
  • the value of the name content attribute for all a, applet, area, embed, form, frameset, img, and object elements in the active document that have a non-empty name content attribute, and
  • the value of the id content attribute of any HTML element in the active document with a non-empty id content attribute.

因此浏览器可能会遍历 DOM 树来解析命名属性。相比之下,getElementById() 只需要在(比如) HashMap 中查找 id。

虽然浏览器可以维护该算法的第一个匹配元素的 HashMap ,但维护该映射会带来性能损失,而这种损失很少能收回成本。相比之下,浏览器不断地通过 id 查找元素,因此保留 id 映射是值得的。

关于javascript - 调用方法比从内存中检索内容更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30584598/

相关文章:

javascript - 自动化批处理脚本 - 在 Photoshop 中将文件名转换为文本

javascript - 未调用隔离范围函数(多个日期选择器)

javascript - React JSX 编辑风格

html - 为什么我的超链接 div 横跨整个页面?

html - Bootstrap 我想在桌面上有五列布局,但在移动设备上有两列

javascript - ContentEditable div - 更新内部 html 后设置光标位置

javascript - 如何从jquery子方法获取字符串?

html - 100% 缩放时看起来不错,但当我缩小时,一切都错了

javascript - 使用javascript遍历html嵌套列表

javascript - 关于 document.addEventListener ('mousemove' , function (e) { 的新手问题