Favorite Loop Benchmark

Thanks to a suggestion from Johnathan Snook, here is a summary of the results of the benchmarking I did on my favorite loop:

Method 1 uses for (var i=0; i<test.length; i++)
Method 2 uses for (var i=0, l=test.length; i<l; i++)
Method 3 uses for (var i=0, o; o=test[i]; i++)

1000 Iterations
Method Firefox 1.5 PC IE 6.0 PC Safari
1 0ms 16ms 11ms
2 0ms 0ms 12ms
3 0ms 0ms 10ms
10000 Iterations
Method Firefox 1.5 PC IE 6.0 PC Safari
1 31ms 32ms 125ms
2 16ms 15ms 117ms
3 16ms 16ms 96ms
100000 Iterations
Method Firefox 1.5 PC IE 6.0 PC Safari
1 297ms 266ms 1937ms
2 296ms 250ms 1924ms
3 250ms 203ms 1878ms

Here’s a link to the script I used for benchmarking.

2 Responses to “Favorite Loop Benchmark”

  1. Mike Haugland said on April 15th, 2006 at 6:39 pm

    Just adding the results of the test for Opera 9.0 weekly build 8367.

    1,000 Iterations
    ———————
    1. 0ms
    2. 0ms
    3. 0ms

    10,000 Iterations
    ———————
    1. 40ms
    2. 30ms
    3. 30ms

    100,000 Iterations
    ———————
    1. 340ms
    2. 341ms
    3. 280ms

    Doing the test multiple times resulted in different results, but method 3 was consistently the fastest.

  2. Danilo said on April 16th, 2006 at 6:34 am

    Unfortunately the loops as shown are not equilivant folks.

    Try running the 3rd one with 0, “”, false, or null as any one of the array values instead of the “1 to iterations” integers within the test array, and you’ll find that your looping will not loop around all of the elements in the array, but rather stop at the first ocurance of 0, “”, or null.

    I suppose that if you can guarantee that you’ll only ever have non-0, non-”", non-false, non-null data in your array you might be able to get away with using this type of construct, but even then, you be giving up guaranteed working for just a few milliseconds. And even at 100,000 iterations (when’s the last time anyone really needed an array that large?), in the worst performing browser, the difference is only 46 milliseconds, which isn’t going to be noticable.