childnodes-vs-getElementsByTagName

JavaScript performance comparison

Revision 3 of this test case created by

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div id="div">
  <div>
    <div>
      <ul>
        <li>
        </li>
      </ul>
    </div>
  </div>
</div>
      
<script>
Benchmark.prototype.setup = function() {
  var div = document.getElementById("div");
  
  function enumerate1(node) {
    var childNodes = node.childNodes;
    for (var i = 0, l = childNodes.length; i < l; i++) {
      if (childNodes[i].nodeType == 1) {
        enumerate1(childNodes[i]);
      }
    }
  }
  
  function enumerate2(node) {
    var childNodes = [].slice.call(node.getElementsByTagName("*"));
  
    for (var i = 0, l = childNodes.length; i < l; i++) {}
  }
  
  function enumerate3(node) {
    var childNodes = node.children;
    for (var i = 0, l = childNodes.length; i < l; i++) {
        enumerate3(childNodes[i]);
    }
  }
  
  function enumerate4(node) {
    for (node = node.firstChild; node; node = node.nextSibling) {
       if (node.nodeType == 1) {
         enumerate4(node);
       }
    }
  }
  function enumerate5(node) {
    var childNodes= node.querySelectorAll("*");
    for (var i = 0, l = childNodes.length; i < l; i++) {}
  }
  function enumerate6(node) {
     $(node).find("*").each(function() {});
  }

};
</script>

Preparation code output

<div id="div"> <div> <div> <ul> <li> </li> </ul> </div> </div> </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
childNodes
enumerate1(div);
pending…
getElementsByTagName
enumerate2(div);
pending…
children
enumerate3(div);
pending…
firstChild
enumerate4(div);
pending…
querySelectorAll
enumerate5(div);
pending…
jquery
enumerate6(div);
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.

0 Comments