我做了几次迭代测试来测试 Document.querySelector
的效率和 Element.querySelector
.
标记:
<form>
<input type="text" />
</form>
脚本:
查询 Document.querySelector
begin = performance.now();
var
i = 0,
iterations = 999999;
for ( i; i < iterations; i++ )
{
element = document.querySelector('[type="text"]');
}
end = performance.now();
firstResult = end - begin;
查询 Element.querySelector
begin = performance.now();
var
i = 0,
iterations = 999999,
form = document.querySelector('form');
for ( i; i < iterations; i++ )
{
element = form.querySelector('[type="text"]');
}
end = performance.now();
secondResult = end - begin;
日志:
console.log( firstResult ); // 703.7450000001118
console.log( secondResult ); // 1088.3349999999627
日志 对我来说太棒了,因为我认为 Element.querySelector
仅查询元素和 Document.querySelector
的后代节点查询当前文档的所有节点,对吗?
为什么会得到这个结果?
最佳答案
根据我上面的评论,选择器会考虑整个文档,然后过滤项目以检查它们是否是目标的后代。所以它很可能仍然需要扫描整个 DOM 树,就像 document.querySelector
需要做的那样。
有一个问题的讨论(这仍然是当前的行为)here .您会在下面的代码示例中看到结果包含了 span,因为它不能单独查询 foo
下的项目。
代码:
document.body.innerHTML = '<div><p id="foo"><span></span></p></div>';
var foo = document.getElementById('foo');
alert( foo.querySelectorAll('div span').length);
关于javascript - 为什么 Document.querySelector 比 Element.querySelector 更高效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32430923/