hasOwnProperty vs. for-in (v17)

Revision 17 of this benchmark created on


Description

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

Preparation HTML

<script>
  var hasOwn = {}.hasOwnProperty;
  var globalSum = 0;
  var MyObj2={};
  var MyObj = new (function() {
   for (var i=0; i< 50;i++) this["s"+i+"e"] = MyObj2["s"+i+"e"]= i;
  })();
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Using hasOwnProperty
var sum=0;
for (var key in MyObj) 
 if (MyObj.hasOwnProperty(key)) 
  sum += MyObj[key];
globalSum+=sum;
ready
Using generic hasOwnProperty
var sum=0;
for (var key in MyObj) 
  if (hasOwn.call(MyObj, key)) 
    sum += MyObj[key];
globalSum+=sum;
ready
Raw
var sum=0;
for (var key in MyObj) 
  sum += MyObj[key];
globalSum+=sum;
ready
Object.keys().forEach()
var sum=0;
Object.keys(MyObj).forEach(function (key) {
  sum += MyObj[key];
});
globalSum+=sum;
ready
Object.keys() for loop
var sum=0;
var keys = Object.keys(MyObj);
for (var i = 0; i < keys.length; i++) 
  sum += MyObj[keys[i]];
globalSum+=sum;
ready
Object.keys() cache length for loop
var sum=0;
var keys = Object.keys(MyObj);
var length = keys.length;
for (var i = 0, val = 0; i < length; i++) 
  sum += MyObj[keys[i]];
globalSum+=sum;
ready
Raw on plain object
var sum=0;
for (var key in MyObj2) 
  sum += MyObj2[key];
globalSum+=sum;
ready

Revisions

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