Loop Faster

nzakas has a great presentation about speeding up Javascript loops but it applies to any language that uses C-like loop structures.

The first principle is not to call a function in the comparison, if the compared value doesn't change. (This is pseudocode by the way.) Bad:

for( i=0; i < a.length(); i++)

Better:

len = a.length();
for( i=0; i < len; i++ )

The second principal is to count down rather than up. This is better:

l = a.length() - 1;
for( ; l >= 0; l-- )

The next optimization should be obvious:

l = a.length();
for( ; l-- ; )

And since we're not initializing or testing:

l = a.length();
while( l-- )

The speedup in interpreted languages is huge, but even in compiled languages, there are speedups because there's typically a "not equal to zero" instruction, or something that can leverage a comparison to zero.

Additionally, this code is easier to debug once you understand the idiom.