hasOwnProperty vs. for-in (v10)

Revision 10 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 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
With hasOwnProperty
for (var i in MyObj) {
 if (MyObj.hasOwnProperty(i)) {
  var val = MyObj[i];
 }
}
ready
With Generic
for (var i in MyObj) {
  if (hasOwn.call(MyObj, i)) {
    var val = MyObj[i];
  }
}
ready
Without
for (var i in MyObj) {
  var val = MyObj[i];
}
ready
Object.keys().forEach
var keys = Object.keys(MyObj);
var max = keys.length;
for (var i = 0; i < max; i++) {
  var val = MyObj[i];
};
ready
Object.keys for loop
var keys = Object.keys(MyObj);
for (var i = 0; i < keys.length; i++) {
  var val = MyObj[i];
};
ready

Revisions

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