object keys vs for loop

JavaScript performance comparison

Revision 6 of this test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function Panda(){}
    Panda.prototype.eats = "bamboo";
    Panda.prototype.climbs = "very small rocks";
    Panda.prototype.lives_in = "China";
   
    var p = new Panda(),
        o = {};
   
    for (var i = 0, len = 1000; i < len; i += 1) {
        o[i] = i * Math.random();
    }
};
</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 (short)
var keys = Object.keys(p),
    len = keys.length,
    i = -1,
    r = {};

while (len > (i += 1)) {
    var k = keys[i];
    r[k] = p[k];
}

return r;

 
pending…
For-in (short)
var prop,
    r = {};

for (prop in p) {
    if (p.hasOwnProperty(prop)) {
        r[prop] = p[prop];
    }
}

return r;
pending…
Object.keys (long)
var keys = Object.keys(o),
    len = keys.length,
    i = -1,
    r = {};

while (len > (i += 1)) {
    var key = keys[i];
    r[key] = o[key];
}

return r;
pending…
For-in (long)
var prop,
    r = {};

for (prop in o) {
    if (o.hasOwnProperty(prop)) {
        r[prop] = o[prop];
    }
}

return r;
pending…
for scoped var (short)
var r = {};

for (var i = 0, keys = Object.keys(p), key, len = keys.length; i < len; i += 1) {
  key = keys[i];
  r[key] = o[key];
}

return r;
pending…
for (short)
var r = {};
var keys = Object.keys(p);
var key;

for (var i = 0, len = keys.length; i < len; i += 1) {
  key = keys[i];
  r[key] = o[key];
}

return r;
pending…
for scoped var (long)
var r = {};

for (var i = 0, keys = Object.keys(o), key, len = keys.length; i < len; i += 1) {
  key = keys[i];
  r[key] = o[key];
}

return r;
pending…
for (long)
var r = {};
var keys = Object.keys(o);
var key;

for (var i = 0, len = keys.length; i < len; i += 1) {
  key = keys[i];
  r[key] = o[key];
}

return r;
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