each method vs. for in

JavaScript performance comparison

Revision 2 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 key = null;
       
        for(key in target) {
            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…

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