for-in versus Object.keys(..).forEach(..)

JavaScript performance comparison

Revision 3 of this test case created

Info

Testing if the perf hit for Object.keys(..).forEach(..) is enough to matter as compared to for-in.

Preparation code

<script>
// pre-ES5 polyfill for Object.keys()
Object.keys=Object.keys||function(o,k,r){r=[];for(k in o)r.hasOwnProperty.call(o,k)&&r.push(k);return r}

// pre-ES5 polyfill for Array.prototype.forEach()
Array.prototype.forEach||(Array.prototype.forEach=function(a,b){for(var c=0,d=this.length;d>c;++c)a.call(b,this[c],c,this)});

function iterate1() {
   var ret = "", i = 0;
   for (i in obj) {
      ret += obj[i];
   }
   return ret;
}

function iterate2() {
   var ret = "", i = 0;
   var ks = Object.keys(obj);
   for(var i=0; i<ks.length; i++)
      ret += obj[ ks[ i ]];
 
}

// object with 10 keys in it
var obj = {
   
};

var j=0;
while(j < 5000) {
  obj[ j.toString() ] = j.toString();
  j++;
}

var tmp;
</script>
<script>
Benchmark.prototype.setup = function() {
    tmp = "";
};
</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
tmp += iterate1();
pending…
Object.keys(..).forEach(..)
tmp += iterate2();
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