object-looping

JavaScript performance comparison

Revision 4 of this test case created by Jonathan Perry

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var obj = {
      a: 1,
      b: 2,
      c: 3,
      d: 4,
      f: 5
    },
    hasOwnProperty = Object.prototype.hasOwnProperty,
    keys = Object.keys(obj);
   
    function forInIf(obj) {
      var key, value;
      for (key in obj) {
        if (hasOwnProperty.call(obj, key)) {
          value = obj[key];
        }
      }
    }
   
    function forInNotHasTrue(obj) {
      var key, value;
      for (key in obj) {
        if (!hasOwnProperty.call(obj, key)) {
          continue;
        } else {
          value = obj[key];
        }
      }
    }
   
    function objectKeysForEach(obj) {
      Object.keys(obj).forEach(withKey);
    }
   
    function keysForEach(keys) {
      keys.forEach(withKey);
    }
   
    function forLoop(obj) {
      var key, value;
      for (var keys = Object.keys(obj), i = 0, j = keys.length; i < j; i++) {
        key = keys[i];
        value = obj[key];
      }
    }
   
    function each(obj, fn) {
      var key;
      for (key in obj) {
        if (hasOwnProperty.call(obj, key)){
          fn.call(obj, obj[key])
        }
      }
    }
   
    function forInIfEquals(obj) {
      var key, value;
      for (key in obj) {
        if (hasOwnProperty.call(obj, key) === true) {
          value = obj[key];
        }
      }
    }
   
    function forInHasNotTrue(obj) {
      for (key in obj) {
        if (hasOwnProperty.call(obj, key) !== true) {
          continue;
        } else {
          value = obj[key];
        }
      }
    }
   
    function withKey(key) {
       value = obj[key];
    }
   
    function withValue(value) {
       return value;
    }
};
</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
for in, if (true)
forInIf(obj);
pending…
for in, continue (!hasOwnProperty)
forInNotHasTrue(obj);
pending…
Object keys
objectKeysForEach(obj);
pending…
keys
keysForEach(keys);
pending…
for
forLoop(obj);
pending…
each
each(obj, withValue);
pending…
for in, if (=== true)
forInIfEquals(obj);
 
pending…
for in, continue (!== true)
forInHasNotTrue(obj);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment