hasOwnProperty vs. for-in (v2)

Revision 2 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] = 'x';
   document.getElementById('title-1').innerHTML += ' (' + count + ')';
   document.getElementById('title-2').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.