hasOwnProperty Performance Analysis

JavaScript performance comparison

Test case created by Marcus Pope

Info

This tests the performance of hasOwnProperty on objects with actual prototype extensions. This will include the performance loss of walking the prototype chain.

This test also compares the performance loss of hasOwnProperty calls versus the performance loss of simply adding another line of code to a for loop, which should prove to be very similar losses in performance.

Preparation code

<script>
  var hasOwn = {}.hasOwnProperty;
  var i = -1,
  count = +location.hash.slice(2) || 50;
 
  while (++i < count) {
      Object.prototype['test' + i] = function() {
         /* function body not necessary */
      }
  }
  var MyObj = (function() {
      var i = -1,
      result = {};
      while (++i < count) result[i] = i;
      return result;
  })();

</script>

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Using hasOwnProperty
for (var key in MyObj) {
 if (MyObj.hasOwnProperty(key)) {
  var val = MyObj[key];
 }
}
pending…
Using generic hasOwnProperty
for (var key in MyObj) {
  if (hasOwn.call(MyObj, key)) {
    var val = MyObj[key];
  }
}
pending…
Raw
for (var key in MyObj) {
  var val = MyObj[key];
}
pending…
Raw With Equal Op Count
for (var key in MyObj) {
  var val = MyObj[key];
  var t = val.toString();
}
pending…
Object.keys().forEach()
Object.keys(MyObj).forEach(function (key) {
  var val = MyObj[key];
});
pending…
Object.keys() for loop
var keys = Object.keys(MyObj);
var length = keys.length;
for (var i = 0; i < length; i++) {
  var val = MyObj[keys[i]];
};
pending…
Using hasOwnProperty with Second Op
for (var key in MyObj) {
 if (MyObj.hasOwnProperty(key)) {
  var val = MyObj[key];
  var t = val.toString();
 }
}
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. Here’s a list of current revisions for this page:

0 comments

Add a comment