object keys vs for loop

JavaScript performance comparison

Test case created by John Cockrell

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 * 2;
    }
};
</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…

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