Reply to comment

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.

Reply

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <b> <dd> <dl> <dt> <i> <li> <ol> <u> <ul> <p> <br> <div> <pre> <code> <img><h1><h2><h3><h4> <blockquote>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.

More information about formatting options

.