Why Document.querySelector is more efficient than Element.querySelector

浪尽此生 提交于 2020-04-13 06:18:10

问题


I did a test with few iterations to test efficiency of Document.querySelector and Element.querySelector.

Markup:

<form>
  <input type="text" />
</form>

Script:

Querying with 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;

Querying with 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;

Log:

console.log( firstResult ); // 703.7450000001118

console.log( secondResult ); // 1088.3349999999627

The log is amazing for me because i think that Element.querySelector query only on nodes that is a descendant of the element and Document.querySelector query on all nodes of current document, right?

Why get this result?


回答1:


From my comment above, the selector takes into account the entire document, then filters the items to check if they are descendants of the target. So it's likely that it still needs to scan the entire DOM tree like document.querySelector would need to do.

There is a discussion of the issue (that is still the current behaviour) here. You'll see in the code sample below the span is included as a result, because it can't just query items below foo in isolation.

Fiddle

Code:

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


来源:https://stackoverflow.com/questions/32430923/why-document-queryselector-is-more-efficient-than-element-queryselector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!