2015-09-07 125 views
3

我做了一个测试,迭代次数很少,以测试Document.querySelectorElement.querySelector的效率。为什么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; 

查询查询

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查询的所有节点上目前的文件,对吧?

为什么会得到这样的结果?

+0

如果添加了1000个兄弟节点的形式,你可能会看到文档级搜索下降的表现。 –

+2

测试[here](http://jsperf.com/document-vs-element-queryselectorall-performance/3)显示你的陈述是不正确的 – Tushar

+0

我不知道你的问题的答案,或者你的问题是这是一个很好的基准,但每次调用300微秒的差别似乎不像现实生活中值得担忧的事情。 – 2015-09-07 04:13:47

回答

4

从我上面的评论中,选择器考虑了整个文档,然后过滤项目以检查它们是否是目标的后代。所以很可能它仍然需要扫描整个DOM树,如document.querySelector需要做的。

有一个问题的讨论(这仍然是当前的行为)here。您会在下面的代码示例中看到跨度作为结果包含在内,因为它不能单独查询foo以下的项目。

Fiddle

代码:

document.body.innerHTML = '<div><p id="foo"><span></span></p></div>'; 
var foo = document.getElementById('foo'); 
alert(foo.querySelectorAll('div span').length); 
相关问题