hasOwnProperty vs. for-in (v6)

Revision 6 of this benchmark created 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 = 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() {
   myObj = setup();
  };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
With hasOwnProperty
var i = 3;
if (MyObj.hasOwnProperty(i)) { return 1+1;}
ready
With Generic
var i = 3;
if (hasOwn.call(MyObj, i)) { return 1+1;}
 
ready
With Square Brackets
var i = 3;
if (MyObj[i]) { return 1+1;}
ready

Revisions

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