NodeList vs. array iteration

JavaScript performance comparison

Revision 3 of this test case created by

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>
  </ul>
</div>
<script>
  function toArray(collection) {
   var result = [],
       i = -1;
   while (result[++i] = collection[i]) {};
   result.length--;
   return result;
  }
</script>
    

Preparation code output

<div> <ul> <li><a href="#">item 1</a></li> <li><a href="#">item 2</a></li> <li><a href="#">item 3</a></li> </ul> </div>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Live List
var liveList = document.getElementsByTagName('a');
for (var i = 0, length = liveList.length; i < length; i++) {
 liveList[i].nodeName;
}
pending…
Static List
var statList = document.querySelectorAll('a');
for (var i = 0, length = statList.length; i < length; i++) {
 statList[i].nodeName;
}
pending…
Array of Live List
var liveArr = toArray(document.getElementsByTagName('a'));
for (var i = 0, length = liveArr.length; i < length; i++) {
 liveArr[i].nodeName;
}
pending…
Array of Static List
var statArr = toArray(document.querySelectorAll('a'));
for (var i = 0, length = statArr.length; i < length; i++) {
 statArr[i].nodeName;
}
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.

4 Comments

John-David Dalton commented :

Actually this revision (Revision 3) misses the point and is testing the method to acquire+convert results combined with property access instead of just testing property access speed.

Scott Sauyet commented :

My thought on seeing revision 1 was that it seemed to miss the point. Do you have a common use for the type of code in revision 1? Do you cache a list of search results and iterate over it many times?

For me, usually iteration happens exactly once, so the acquire/convert speed is integral to the test.

John-David Dalton commented :

Do you have a common use for the type of code in revision 1? Do you cache a list of search results and iterate over it many times?

Yes, caching results and then iterating over them again and again is the pattern popularized by frameworks like jQuery.

Scott Sauyet commented :

I suppose so, but even then, except when the result is a wrapper for a single element, I rarely keep them long enough that I can ignore the cost of acquiring them.