Object.keys vs hasOwnProperty with Hash Table objects (v32)

Revision 32 of this benchmark created by jonbo on


Description

A small change compared to edit 31 where your treating an object as a hash table/map (deleting/adding keys). For-in becomes incredibly slow on V8 (node, chrome, opera).

A good read: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#52-the-object-being-iterated-is-not-a-simple-enumerable

Setup

var i;
    var key;
    var keys;
    var l;
    var value;
    var hasOwnProperty = {}.hasOwnProperty;
    var obj = {
      'a': 1,
      'b': 2,
      'c': 3,
      'd': 4,
      'e': 5,
      'f': 6,
      'g': 7,
      'h': 8,
      'i': 9,
      'j': 10
    };
    
    delete obj['h'];
    obj['k'] = 11;

Test runner

Ready to run.

Testing in
TestOps/sec
hasOwnProperty
for (key in obj) {
  if (obj.hasOwnProperty(key)) {
    value = obj[key];
  }
}
ready
Object.keys
keys = Object.keys(obj);
for (i = 0, l = keys.length; i < l; i++) {
  value = obj[keys[i]];
}
ready
Object.keys with forEach
keys = Object.keys(obj).forEach(function(key) {
  value = obj[key];
});
ready
Plain for...in
for (key in obj) {
  value = obj[key];
}
ready

Revisions

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