Dereference Object Property Path From String (v2)

Revision 2 of this benchmark created by Drew Noakes on


Description

Fastest way to dereference an object property path stored in a string.

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;
    }
    
    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 deref2(obj, s) {
      var i = 0;
      var bits = s.split('.');
      while (obj && i < bits.length)
        obj = obj[bits[i++]];
      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 loop
deref(obj, 'a.b.x')
ready
deref recursive
derefrecursive(obj, 'a.b.x'.split("."))
ready
deref loop 2
// Unlike deref, this version doesn't change the type of the
// variable within the function. This may give native code
// generators an easier time.
deref2(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