Access to nodes via querySelectorAll vs getElementsByTagName

JavaScript performance comparison

Revision 5 of this test case created by Jacob Swartwood

Info

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

Preparation code

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

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
querySelectorAll
var nodes = document.querySelectorAll('a');
nodes[0];
nodes[1];
nodes[2];
nodes[3];
nodes[4];
nodes[5];
nodes[6];
nodes[7];
nodes[8];
nodes[9];
nodes[10];
nodes[11];
nodes[12];
nodes[13];
nodes[14];
nodes[15];
nodes[16];
pending…
getElementsByTagName
var nodes = document.getElementsByTagName('a');
nodes[0];
nodes[1];
nodes[2];
nodes[3];
nodes[4];
nodes[5];
nodes[6];
nodes[7];
nodes[8];
nodes[9];
nodes[10];
nodes[11];
nodes[12];
nodes[13];
nodes[14];
nodes[15];
nodes[16];
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment