hasOwnProperty vs. for-in (v15)

Revision 15 of this benchmark created on


Description

Test performance hit of calling x.hasOwnProperty() in a for-in loop.

Preparation HTML

<script>
  var hasOwn = {}.hasOwnProperty;
  var val = 0;
  
  var MyObj = (function() {
   var i = -1,
       result = {},
       count = +location.hash.slice(2) || 50;
   while (++i < count) result[i] = i;
   i = 0;
   while (++i < 4) document.getElementById('title-' + i).innerHTML += ' (' + count + ')';
   return result;
  })();
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Using hasOwnProperty
for (var key in MyObj) {
 if (MyObj.hasOwnProperty(key)) {
  val += +MyObj[key];
 }
}
ready
Using generic hasOwnProperty
for (var key in MyObj) {
  if (hasOwn.call(MyObj, key)) {
    val += +MyObj[key];
  }
}
ready
Raw
for (var key in MyObj) {
  val += +MyObj[key];
}
ready
Object.keys().forEach()
Object.keys(MyObj).forEach(function (key) {
  val += +MyObj[key];
});
ready
Object.keys() for loop
var keys = Object.keys(MyObj);
for (var i = 0; i < keys.length; i++) {
  val += +MyObj[keys[i]];
};
ready
Object.keys() cache length for loop
var keys = Object.keys(MyObj);
var length = keys.length;
for (var i = 0, val = 0; i < length; i++) {
  val += +MyObj[keys[i]];
};
ready

Revisions

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