hasOwnProperty vs. for-in (v16)

Revision 16 of this benchmark created by ryan 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
Object.keys(MyObj).forEach(function (i){
  var val = MyObj[i];
});
ready
Object.keys for loop
var keys = Object.keys(MyObj);
var max = keys.length;
for (var i = 0; i < max; i++) {
  var val = MyObj[i];
};
ready
var max = Object.keys(MyObj).length;
do {  
var val = MyObj[max];
} while (--max)
ready

Revisions

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