Access to nodes via querySelectorAll vs getElementsByTagName (v9)

Revision 9 of this benchmark created by Romanito on


Description

we discovered that calling getelementsbytagname('DIV') is a way faster than queryselectorall('DIV') http://www.nczonline.net/blog/2010/09/28/why-is-getelementsbytagname-faster-that-queryselectorall

the reason being that the former returns an HTMLCollection (live list) and the later a NodeList (static list). To go further we will see if accessing properties of a static list compensates the time to create it

Revision 9: However when making a more complex query (typical use of querySelectorAll), using getElementsByTagName and making the filtering by code is still slower than using querySelectorAll.

Preparation HTML

<div>
  <ul>
    <li><a href="#1">item 1</a></li>
    <li><a href="#2">item 2</a></li>
    <li><a href="#1">item 3</a></li>
    <li><a href="#2">item 4</a></li>
    <li><a href="#1">item 5</a></li>
    <li><a href="#2">item 6</a></li>
    <li><a href="#1">item 7</a></li>
    <li><a href="#2">item 8</a></li>
    <li><a href="#1">item 9</a></li>
    <li><a href="#2">item 10</a></li>
    <li><a href="#1">item 11</a></li>
    <li><a href="#2">item 12</a></li>
    <li><a href="#1">item 13</a></li>
    <li><a href="#2">item 14</a></li>
    <li><a href="#1">item 15</a></li>
    <li><a href="#2">item 16</a></li>
    <li><a href="#1">item 17</a></li>
  </ul>
</div>

Test runner

Ready to run.

Testing in
TestOps/sec
querySelectorAll
var nodes = document.querySelectorAll('a[href*="1"]');
for (var i=0; i<nodes.length; i++) {
  nodes[i];
}
ready
getElementsByTagName
var nodes = document.getElementsByTagName('a');
for (var i=0; i<nodes.length; i++) {
  var node = nodes[i];
  if (node.href && node.href.indexOf('1') > -1) {
    node;
  }
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.