each method vs. for in

JavaScript performance comparison

Revision 3 of this test case created

Info

A test of function wrappers compared to the long hand.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    Object.applyEach = function(target, callback) {
        var key = null;
       
        for(key in target) {
            if(target.hasOwnProperty(key)) {
                callback.apply(null, arguments);
            }
        }
    };
   
    Object.callEach = function(target, callback) {
        var keys = Object.keys(target);
       
        for(var i = 0, len = keys.length; i < len; i++) {
            var key = keys[i];
            if(target.hasOwnProperty(key)) {
                callback.call(null, target, callback);
            }
        }
    };
   
    Object.invokeEach = function (target, callback) {
      var key = null;
     
      for (key in target) {
        if (target.hasOwnProperty(key)) {
          callback(target, callback);
        }
      }
    };
   
    var testObject = {},
        copyTo = null;
   
    for(var i = 0; i < 100; i += 1) {
        testObject[i] = i * new Date().getTime();
    }
};
</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
applyEach
Object.applyEach(testObject, function(i) {
    copyTo = i;
});
pending…
callEach
Object.callEach(testObject, function(i) {
    copyTo = i;
});
pending…
invokeEach
Object.invokeEach(testObject, function(i) {
    copyTo = i;
});
pending…
Normal loop
var key = null;

for(key in testObject) {
    if(testObject.hasOwnProperty(key)) {
        copyTo = i;
    }
}
pending…
object.keys
var keys = Object.keys(testObject);

for (var i = 0, len = keys.length; i < len; i++) {
    copyTo = i;
}
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:

2 comments

witek commented :

Object.keys is undefined here. Opera 12.00 alpha.

Oliver Caldwell commented :

@witek Yep, thats the problem with using Object.keys. It is a very new feature. So you will have to do feature detection to run the fastest loop for that browser.

Add a comment