Node tree traversal

Benchmark created by biziclop on


Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
  window.tr = function() {
   var a = arguments;
   for (var i = 0; i < a.length; i++) a[i] = String(a[i]);
   var s = Array.prototype.join.call(a, ' ');
   var n = document.getElementById('message');
   n.value += s + '\n';
  }
  
  
  
  function makeXML(N, depth, o, isRoot) {
   o.i++;
  
   var s = '<a' + depth + '>';
   if (depth > 0) {
    var i = N;
    while (i--) s += makeXML(N, depth - 1, o);
   } else {
    s += 'A';
    o.i++;
   }
   s += '</a' + depth + '>';
  
   if (isRoot) {
    var x = document.createElement('div');
    x.innerHTML = s;
    return x;
   }
   return s;
  }
  
  var o = {
   i: 0
  };
  var x = makeXML(4, 4, o, true);
  tr('Total Nodes:', o.i);
  NN = o.i;
  
  var CC = 0;
  
  function tt1pre(x) { // 306000 op/sec
   var fc;
   while (x) {
    CC++; //tr(x.nodeType); // x is child
    if (fc = x.firstChild) tt1pre(fc);
    x = x.nextSibling;
   }
  }
  
  function tt1post(x) { // 338000 op/sec
   var fc;
   do {
    CC++; //tr(x.nodeType); // x is child
    if (fc = x.firstChild) tt1post(fc);
   } while (x = x.nextSibling);
  }
  
  function tt2a(x) { // 215500
   CC++; //tr(x.nodeType);
   if (x = x.childNodes) {
    var i = x.length;
    while (i--) tt2a(x[i]);
   }
  }
  
  function tt2b(x) { // 224000
   CC++; //tr(x.nodeType);
   if (x = x.childNodes) {
    var i = x.length;
    while (i) tt2b(x[--i]);
   }
  }
  
  CC = 0;
  tt1pre(x);
  tr('tt1pre', CC);
  
  CC = 0;
  tt1post(x);
  tr('tt1post', CC);
  
  CC = 0;
  tt2a(x);
  tr('tt2a', CC);
  
  CC = 0;
  tt2b(x);
  tr('tt2b', CC);
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
nextSibling, pre-test
tt1pre(x);
ready
nextSibling, post-test
tt1post(x);
ready
childNodes, post-dec i
tt2a(x);
ready
childNodes, pre-dec i
tt2b(x);
ready

Revisions

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

  • Revision 1: published by biziclop on