for-in versus Object.keys(..) for loop (v29)

Revision 29 of this benchmark created on


Description

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

Preparation HTML

<script>
var hasOwn = Object.prototype.hasOwnProperty;

// 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}

function iterate1() {
   var v = "", i;
   for (i in obj) {
      if (hasOwn.call(obj, i)) {
          v = obj[i];
      }
   }
}

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

function iterate3() {
   var v = "", i = 0;
   for (i in obj) {
          v = obj[i];
   }
}


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

Test runner

Ready to run.

Testing in
TestOps/sec
for-in
iterate1();
ready
Object.keys(..) for loop
iterate2();
ready
for-in (no hasown)
iterate3();
ready

Revisions

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