Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Document.querySelector is more efficient than Element.querySelector

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?

like image 251
Alexandre Thebaldi Avatar asked Sep 07 '15 04:09

Alexandre Thebaldi


1 Answers

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);
like image 107
Evan Trimboli Avatar answered Sep 30 '22 18:09

Evan Trimboli