Dereference Object Property Path From String (v4)

Revision 4 of this benchmark created 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++]];
    return obj;
  }
  
  
  //I left this here out of deference to the OP, but it didn't return correct result when I tested it locally - KC
  function derefrecursive(obj, s, i) {
    if (i === undefined) i = 0;
    if (i < s.length) return derefrecursive(obj[s[i]], s, i + 1);
    return obj;
  }
  
  //Function constructor method -- optimized for repeatedly dereferencing the same path (memoizedLookupFunction). Performs slower than eval() if you aren't reusing the path (lookupFunction).
  function lookupFunction(obj, path) {
    var func = Function("obj", "return obj." + path + ";");
    return func(obj);
  }
  
  var derefFuncs = {};
  function memoizedLookupFunction(obj, path) {
    if (!derefFuncs[path]) { 
      derefFuncs[path] = Function("obj", "return obj." + path + ";");
    }
    return derefFuncs[path](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 loop
deref(obj, 'a.b.x')
ready
deref recursive
derefrecursive(obj, 'a.b.x'.split("."))
ready
worst case lookup function
lookupFunction(obj, 'a.b.x')
ready
best case memoized lookup function
memoizedLookupFunction(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