Dereference Object Property Path From String

Benchmark created by James Wilkins on


Setup

function index(obj, i) {
    return obj[i]
  }
  var obj = {
    a: {
      b: {
        x: 0
      }
    }
  };
  
  function deref(obj, s) {
    var i = 0;
    s = s.split('.');
    while (obj && i < s.length)
      obj = obj[s[i++]];
  }
  
  function derefrecursive(obj, s, i) {
    if (i === undefined) i = 0;
    if (i < s.length) return derefrecursive(obj[s[i]], s, i + 1);
    return obj;
  }

Test runner

Ready to run.

Testing in
TestOps/sec
split + reduce
'a.b.x'.split('.').reduce(index, obj)
ready
eval
eval('obj.' + 'a.b.x')
ready
deref recursive
derefrecursive(obj, 'a.b.x'.split("."))
ready
deref loop
deref(obj, 'a.b.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 James Wilkins on
  • Revision 2: published by Drew Noakes on
  • Revision 3: published by Stefan on
  • Revision 4: published on