Dereference Object Property Path From String (v3)

Revision 3 of this benchmark created by Stefan 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 deref2(obj, s) {
      var i = 0;
      var bits = s.split('.')
      while (obj && i < bits.length)
        obj = obj[bits[i++]];
      return obj;
    }
    
    var cache = {}
    
      function dynamicFnWithCache(object, path) {
        var fn = cache[path]
        if (!fn) {
          fn = cache[path] = new Function('arg', 'return arg.' + path)
        }
        return fn.call(null, object)
      }
    
    
      function deref2Arr(obj, bits) {
        var i = 0;
        while (obj && i < bits.length)
          obj = obj[bits[i++]];
        return obj;
      }
    
    var cache2 = {}
    
      function dynamicFnWithCacheArr(object, p) {
        var path = p.join('.')
        var fn = cache2[path]
        if (!fn) {
          fn = cache2[path] = new Function('arg', 'return arg.' + path)
        }
        return fn.call(null, object)
      }
    
    var cache3 = {}
    
      function dynamicFnWithCacheArrToString(object, p) {
        var path = p.toString()
        var fn = cache3[path]
        if (!fn) {
          fn = cache3[path] = new Function('arg', 'return arg.' + p.join('.'))
        }
        return fn.call(null, object)
      }
    
    function getIn(obj, bits) {
        for(var i = 0, j = bits.length; i < j; ++i) {
            obj = obj[bits[i]];
        }
        return obj;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
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
dynamicFnWithCache
dynamicFnWithCache(obj, 'a.b.x')
ready
deref loop 2 arr
// Unlike deref, this version doesn't change the type of the
// variable within the function. This may give native code
// generators an easier time.
deref2Arr(obj, ['a', 'b', 'x'])
ready
dynamicFnWithCacheArr
dynamicFnWithCacheArr(obj, ['a', 'b', 'x'])
ready
dynamicFnWithCacheArrToString
dynamicFnWithCacheArrToString(obj, ['a', 'b', 'x'])
ready
getIn
getIn(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