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

Revision 11 of this benchmark created on


Description

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

Preparation HTML

<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;
   Object.keys(obj).forEach(function(key){
      ret += obj[key];
   });
}

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

// 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;
</script>

Setup

tmp = "";

Test runner

Ready to run.

Testing in
TestOps/sec
for-in
tmp += iterate1();
ready
Object.keys(..).forEach(..)
tmp += iterate2();
ready
for-in with hasOwnProperty() test
tmp += iterate3();
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.