Enumerating vs Iteration on an Array

JavaScript performance comparison

Revision 2 of this test case created

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
For loop - with "i++"
for (var i = 0; i < a.length; i++) 
{
   a[i];
}
pending…
For loop - with "i++" Optimal
var c = a.length;
for (var i = 0; i < c; i++)
{
   a[i];
}
pending…
For loop - with "in"
// "a" must be array 
for (var i in a)
{
    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