object keys vs for loop

JavaScript performance comparison

Revision 8 of this test case created by Tanel Liiv

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var 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(o),
    len = keys.length,
    i = -1,
    r = {};

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

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

for (prop in o) {
    if (o.hasOwnProperty(prop)) {
        r[prop] = o[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…
Regular for-in (short)
var prop,
    r = {};

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

return r;
pending…
Object.keys (short2)
var keys = Object.keys(o),
    i = keys.length,
    r = {};

while (i--) {
    r[keys[i]] = o[keys[i]];
}

return r;
 
pending…
Object.keys (long2)
var keys = Object.keys(o),
    i = keys.length,
    r = {};

while (i--) {
    var 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