Object.keys vs for in for values

JavaScript performance comparison

Revision 33 of this test case created

Preparation code

<script>

</script>
<script>
Benchmark.prototype.setup = function() {
    var keys = Object.keys;
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    var gl = {
      name: 'ABC',
      qb: 'Manning',
      wr: 'calvin',
      te: 'davis'
    };
   
    var params = {
      qb: 'Manning'
    };
   
    var obj = {
      name: function() {
        return params.name || gl.name
      },
      qb: function() {
        return params.qb || gl.qb
      },
      wr: function() {
        return params.wr || gl.wr
      },
      te: function() {
        return params.te || gl.te
      }
    };
};
</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
Object.keys
var props = keys(obj),
  length = props.length,
  index = -1,
  v = {};

while (++index < length) {
  v[props[index]] = obj[props[index]]();
  }
pending…
for-in w/ hasOwnProperty
var v = {};
for (var prop in obj) {
  if (obj.hasOwnProperty(prop)) {
    v[prop] = obj[prop]();
  }
}
pending…
for in with function
function enumerate(o, handler) {
    for (var k in o) {
        o.hasOwnProperty(k) && handler(k, o[k]);
    }
};
var v = {};
enumerate(obj, function(k){
  v[k] = obj[k]();
});
pending…
for-in w/ hasOwnProperty resilient
var v = {};
for (var prop in obj) {
  if (Object.prototype.hasOwnProperty.call(obj, prop)) {
    v[prop] = obj[prop]();
  }
}
pending…
Iterate through keys with Array.forEach
var v = {};
Object.keys(obj).forEach(function (prop) {
  v[prop] = obj[prop];
});
 
pending…
Prototype lookup with undefined
var undef = void 0,
  v = {};
for (var prop in obj) {
  if (obj[prop] === undef) {
    v[prop] = obj[prop]();
  }
}
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