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

JavaScript performance comparison

Test case created by Kyle Simpson


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

Preparation code

// pre-ES5 polyfill for Object.keys()
Object.keys=Object.keys||function(o,k,r){r=[];for(k in 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),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;
      ret += obj[key];

// object with 10 keys in it
var obj = {
   a: "a",
   b: "b",
   c: "c",
   d: "d",
   e: "e",
   f: "f",
   g: "g",
   h: "h",
   i: "i",
   j: "j"

var tmp;
Benchmark.prototype.setup = function() {
    tmp = "";

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
tmp += iterate1();
tmp += iterate2();

Compare results of other browsers


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:

1 comment

byc commented :

When checking hasOwnProperty() in the for-in loop, it becomes significantly slower. In this case, the Object.keys(..) method is faster.

Comment form temporarily disabled.

Add a comment