Period-based JSON object traversal

Benchmark created by David G. Hong on


Preparation HTML

<script>
  var shift = Array.prototype.shift,
      split = String.prototype.split,
      
      
      
      
      
      
      
      r_period = /\./ig;
  
  var traverse1 = function(json, namespace) {
   var tree = split.call(namespace, r_period),
       curr, val = json;
  
   while ((curr = shift.call(tree))) {
    val = val[curr];
   }
  
   return val;
  };
  
  var traverse2 = function(json, namespace) {
   var tree = split.call(namespace, r_period),
       tt = function(obj, keys) {
     if (!keys || keys.length == 0) {
      return obj;
     }
  
     return tt(obj[shift.call(keys)], keys);
       };
   return tt(json, tree);
  };
  
  var o = {
   n: {
    x: {
     y: {
      t: 0,
      s: 1,
      r: {
       b: true
      }
     }
    }
   }
  };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
While loop
traverse1(o, 'n.x.y.r.b');
ready
Recursive
traverse2(o, 'n.x.y.r.b');
ready
Direct referencing via dot notation
o.n.x.y.r.b
ready
Direct referencing via bracket notation
o['n']['x']['y']['r']['b']
ready

Revisions

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

  • Revision 1: published by David G. Hong on