hasOwnProperty vs. for-in

JavaScript performance comparison

Revision 17 of this test case created by

Preparation code

<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

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Using hasOwnProperty
var sum=0;
for (var key in MyObj) 
 if (MyObj.hasOwnProperty(key)) 
  sum += MyObj[key];
globalSum+=sum;
pending…
Using generic hasOwnProperty
var sum=0;
for (var key in MyObj) 
  if (hasOwn.call(MyObj, key)) 
    sum += MyObj[key];
globalSum+=sum;
pending…
Raw
var sum=0;
for (var key in MyObj) 
  sum += MyObj[key];
globalSum+=sum;
pending…
Object.keys().forEach()
var sum=0;
Object.keys(MyObj).forEach(function (key) {
  sum += MyObj[key];
});
globalSum+=sum;
pending…
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;
pending…
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;
pending…
Raw on plain object
var sum=0;
for (var key in MyObj2) 
  sum += MyObj2[key];
globalSum+=sum;
pending…

Compare results of other browsers

Revisions

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

1 Comment

Eamon Nerbonne commented :

Somewhat unusual to see IE beat chrome in every variant!