hasOwnProperty vs. for-in (v4)

Revision 4 of this benchmark created by John-David Dalton 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)) {}
}
ready
With Generic
for (var i in MyObj) {
  if (hasOwn.call(MyObj, i)) {}
}
ready
Without
for (var i in MyObj) {}
ready

Revisions

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