Optimizing Iterating through an Array

25th September 2005 | 2 Comments

I love using arrays, they're just so handy. I recently ran into the problem of finding out if a value already existed in an array. I thought this would be a great time to compare the speed of different loops. I decided to test a For Loop, a While Loop and a different than usual While Loop, where I increment the array’s position in the loop’s condition statement.

I tested these loops on Firefox 1.0.6, Internet Explorer 6, Flash Player 7 and Flash Player 8. Each method was tested three times on a 250,000 item array and I averaged the results. Note: These results are tied directly to the speed of your computer, so speeds may vary.

Execution time in milliseconds (ms)
Method Firefox 1.0.6 Internet Explorer 6.0 Flash 7 SA Player Flash 8 SA Player
For Loop 125 219 391 307
While Loop #1 109 188 297 261
While Loop #2 94 177 286 255

I was thoroughly impressed by Firefox, even in its non optimized state, nothing could touch it. The same can’t be said about Flash. I believe flash’s slowness stems from the fact that the array is being executed on a virtual machine instead of native code. But I’m glad to see the Flash 8 Player got some needed speed boosts in its lastest update.

Here my super optimized method (While Loop #2):

Array.prototype.find = function(x) {
var length = this.length;
var i = -1;

while(++i < length) {
if (this[ i ] == x) {
return true;
}
}
return false;
}

Here is While Loop #1:

Array.prototype.find = function(x) {
var i = 0;
var j = this.length;

while(i < j) {
if (this[ i ] == x) {
return true;
}
i++;
}
return false;
}

And here is the For Loop:

Array.prototype.find = function(x) {
for(var i = 0; i < this.length; i++) {
if (this[ i ] == x) {
return true;
}
}
return false;
}

Update: I ran the test again, but this time iterating backwards. All of the For Loops showed minor improvements (20ms - 30ms faster) except for Flash 7 Standalone player, it jumped from 391ms down to 303ms. While Loops weren’t so fortunate. They all hovered around the same speed as the backwards For Loop.

Execution time in milliseconds (ms)
Backwards Method Firefox 1.0.6 Internet Explorer 6.0 Flash 8 SA Player Flash 7 SA Player
For Loop 104 187 300 303
While Loop #1 99 182 302 312
While Loop #2 94 182 292 303

Discussion

Chester Oakley

EXPERT PROGRAMMER

Jeff

The confidence interval on this is huge. You can’t derive statistically relevant information from 3 tests. The difference in results would have to be pretty much 0 from test to test.

Leave a Comment