childnodes vs getElementsByTagName for child nodes

JavaScript performance comparison

Revision 13 of this test case created

Preparation code

<ul id="test">
  <li></li>
  <li><ul><li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul></li>
  <li></li>
  <li></li>
  <li></li>
</ul>
<script>
Benchmark.prototype.setup = function() {
    var UL = document.getElementById('test');
};
</script>

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
childNodes
var a = UL.childNodes,arr=[];
for(var i=0,j=a.length;i<j;i++)
{
if(a[i].nodeType == 1) arr.push(a[i]);
}
pending…
getElementsByTagName
var a = UL.getElementsByTagName('LI'),arr=[];
for(var i=0,j=a.length;i<j;i++)
{
if(a[i].parentNode == UL) arr.push(a[i]);
}
pending…
3
var a = UL.getElementsByTagName('LI'),arr=[];
for(var i=0,j=a.length;i<j;i++)
{
if(a[i].parentNode == UL) arr[arr.length] = a[i];
}
pending…
4
var a = UL.getElementsByTagName('LI'),arr=[],arrl = arr.length;
for(var i=0,j=a.length;i<j;i++)
{
if(a[i].parentNode == UL) arr[arrl+i] = a[i];
}
pending…
5
var a = UL.getElementsByTagName('LI'),arr=[],i=0,j=a.length,b;
for(;i<j;i++)
{b=a[i];
if(b.parentNode == UL) arr.push(b);
}
pending…
6
var a = UL.childNodes,arr=[],i=0,j=a.length,b;
for(;i<j;i++)
{b=a[i];
if(b.nodeType == 1) arr.push(b);
}
pending…
7
var node,arr = [];
for (node = UL.firstChild; node; node = node.nextSibling) {
         if (node.nodeType == 1) {
           arr.push(node);
         }
      }
pending…
7.1
var a = UL.childNodes,i=0,j=a.length;
for(;i<j;i++)
{
if(a[i].nodeType ^ 1) a.splice(i,1);
}
pending…
6.1
var a = UL.childNodes,arr=[],i=0,j=a.length,b,arrl = arr.length;
for(;i<j;i++)
{b=a[i];
if(b.nodeType == 1) arr[arrl+i] = b;
}
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