object.keys vs for in (v3)

Revision 3 of this benchmark created by Samori Gorse on


Description

Check performance of object.keys vs for in loop.

Setup

var obj = {
      a: 0,
      b: 1,
      c: 2,
      d: 3,
      e: 4,
      f: 5,
      g: 6,
      h: 7,
      i: 8,
      j: 9
    };
    var sum = 0;

Teardown


    console.log(sum);
  

Test runner

Ready to run.

Testing in
TestOps/sec
Object keys and for loop
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
  sum += obj[keys[i]];
}
ready
Object keys and optimized for loop
var keys = Object.keys(obj);
for (var i = 0, l = keys.length; i < l; i++) {
  sum += obj[keys[i]];
}
ready
Object keys and forEach
var keys = Object.keys(obj);
keys.forEach(function(key) {
  sum += obj[key];
});
ready
For in loop with hop
for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    sum += obj[key];
  }
}
ready
For in loop without hop
for (var key in obj) {
  sum += obj[key];
}
ready

Revisions

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