Enumerating vs Iteration on an Array

JavaScript performance comparison

Test case created by Jeremy Osborne

Info

Which is faster:

I'm sure this has been done before, and my gut tells me the answer, but I couldn't find a test and I wanted to see the performance impact before changing some core code I use but I don't own. In other words, this is CYA for me.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var i;
    var a = [];
   
    for (i = 0; i < 10000; i++) {
        a[i] = i;
    }
   
    // export for testing
    window.a = a;
};
</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
Looping through the array using usual for loop iteration
for (var i = 0; i < a.length; i++) {
    // Just check access time.
    a[i];
}
pending…
Looping through an array using an enumeration for loop
for (var i in a) {
    if (a.hasOwnProperty(i)) {
        // Just check access time.
        a[i];
    }
}
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