hasOwnProperty vs. for-in (v5)

Revision 5 of this benchmark created by Mathias Bynens on


Description

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

Example using the Benchmark.params object, which contains parameters and values from the URL hash. Try #count=500 or #count=750.

Preparation HTML

<script>
  var hasOwn = {}.hasOwnProperty,
      MyObj;
  
  function setup() {
   var i = -1,
       result = {},
       count = Benchmark.params.count || 50; // Always provide default values!
   while (++i < count) {
    result[i] = i;
   }
   i = 0;
   while (++i < 4) {
    document.getElementById('extra-' + i).innerHTML = '(' + count + ')';
   }
   return result;
  }
  
  MyObj = setup();
  
  // The init() function is pure magic.
  // When it’s available, it will be executed before every test,
  // and also upon `hashchange`.
  // See http://mths.be/aid
  function init() {
   // Output Benchmark.params to the console if available
   window.console && console.log(Benchmark.params);
   myObj = setup();
  };
</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.