loop-vs-hOP-vs-proto

JavaScript performance comparison

Test case created by WebReflection and last updated

Info

in ES5 we can forget hasOwnProperty() check thanks to the ability to configure properties as non enumerable. In ES6 we have a new property to check in every loop able to screw up things around so we need a check against proto In ES6 backward compatible with ES3 we need both checks ... let's see how much this will impact our code.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var create = Object.create || Object,
        hOP = {}.hasOwnProperty,
        result;
   
    function withoutProto(o) {
      var result = {}, k;
      for (k in o) result[k] = o[k];
      return result;
    }
    function withProto(o) {
      var result = {}, k;
      for (k in o) {
        if(k !== '__proto__')
          result[k] = o[k];
      }
      return result;
    }
    function withHasOwnProperty(o) {
      var result = {}, k;
      for (k in o) {
        if(hOP.call(o, k))
          result[k] = o[k];
      }
      return result;
    }
    function withHasOwnPropertyAndProto(o) {
      var result = {}, k;
      for (k in o) {
        if(k !== '__proto__' && hOP.call(o, k))
          result[k] = o[k];
      }
      return result;
    }
    function objectKeysAndFilter(o) {
      var result = {};
      Object.keys(o).filter(noProto).map(function(key) {
        result[key] = o[key];
      });
      return result;
    }
    function noProto(key) {
      return key !== '__proto__';
    }
};
</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
withoutProto
var i = 0, n = create(null);
n.__proto__ = {};
for (i = 0; i < 50; i++) {
  n[String.fromCharCode(50 + i)] = i;
  result = withoutProto(n);
}
pending…
withProto
var i = 0, n = create(null);
n.__proto__ = {};
for (i = 0; i < 50; i++) {
  n[String.fromCharCode(50 + i)] = i;
  result = withProto(n);
}
pending…
withHasOwnProperty
var i = 0, n = create(null);
n.__proto__ = {};
for (i = 0; i < 50; i++) {
  n[String.fromCharCode(50 + i)] = i;
  result = withHasOwnProperty(n);
}
pending…
withHasOwnPropertyAndProto
var i = 0, n = create(null);
n.__proto__ = {};
for (i = 0; i < 50; i++) {
  n[String.fromCharCode(50 + i)] = i;
  result = withHasOwnPropertyAndProto(n);
}
pending…
objectKeysAndFilter
var i = 0, n = create(null);
n.__proto__ = {};
for (i = 0; i < 50; i++) {
  n[String.fromCharCode(50 + i)] = i;
  result = objectKeysAndFilter(n);
}
pending…

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

Compare results of other browsers

0 comments

Add a comment