hasOwnProperty vs. for-in (v18)

Revision 18 of this benchmark created by Eamon Nerbonne on


Description

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

Preparation HTML

<script>
  var hasOwn = {}.hasOwnProperty;
  var globalSum = 0;
  function ObjF() { for (var i=0; i< 50;i++) this["s"+i+"e"] = i; return this; };
  ObjF.prototype.evilAddition = "something";
  var MyObj = ObjF.call({});
  var MyObj2 = new ObjF();
</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 for ... in loop
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
hasOwnProperty on obj with inherited property
var sum=0;
for (var key in MyObj2) 
 if (MyObj2.hasOwnProperty(key)) 
  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.