Tree traversal - Underscore.loop vs normal js

JavaScript performance comparison

Test case created by Paul

Preparation code

<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="https://raw.github.com/benekastah/underscore.loop/master/dist/underscore.loop.min.js"></script>
 
<script>
Benchmark.prototype.setup = function() {
    var recurseObject = function(obj, action) {
        var prop, item, result, ret;
        ret = [];
        for (prop in obj) {
          if (obj.hasOwnProperty(prop)) {
            item = obj[prop];
            if (typeof item === "object") recurseObject(item, action);
            else ret.push(action.call(obj, prop, item));
          }
        }
        return ret;
        };
   
    var recurseObjectLoop = function(obj, action) {
        var prop, item;
        return _.loop([obj, Object.keys(obj)], function(node, keys, continueArgs) {
          var key, item, nextArgs;
   
          if (keys.length) {
            key = _.first(keys);
            item = node[key];
   
            nextArgs = [node, _.rest(keys), continueArgs];
            if (typeof item === "object") return this.loop(item, Object.keys(item), nextArgs);
            else {
              action.call(node, key, item);
              return this.loop.apply(this, nextArgs);
            }
          } else if (continueArgs) {
            return this.loop.apply(this, continueArgs);
          }
        });
        };
   
    var tree = {
      a: 1,
      b: 2,
      c: 3,
      d: {
        a: 1,
        b: 2,
        c: 3,
        d: {
          e: 4,
          f: 5,
          g: 6
        }
      }
    };
   
    var mult2 = function(key, value) {
        this[key] = value * 2;
        };
};
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Native JS
recurseObject(tree, mult2);
pending…
Underscore.loop
recurseObjectLoop(tree, mult2);
pending…

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

Compare results of other browsers

0 comments

Add a comment