DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Loop Through An Array Without Wasteful Lookups

04.03.2005
| 167799 views |
  • submit to reddit
        Looking up the length of an array on each iteration of a loop is slow and inefficient (if the length of the array isn't changing).

If it's OK to iterate from back to front:
for ( var i=myArray.length-1; i>=0; --i ){
  ...
}

If you need to go from front to back:
for ( var i=0, len=myArray.length; i<len; ++i ){
  ...
}
    

Comments

Snippets Manager replied on Wed, 2011/07/20 - 11:38pm

I get a parse error in Safari when I run: for ( var i=0, len=myArray.length; i So I just changed it to: for ( var i=0, i And it fixed the error. I'll deal with optimizations in the later stages.

Greg Nonya replied on Wed, 2006/07/19 - 4:56pm

There is a difference of about 10-20 ms if iterating front to back, but thats only on larger size array. Personaly I prefer/use this: var arLen=myArray.length; for ( var i=0, len=arLen; i It is as efficient as back to front iter. and it keeps items in order they have been added

Snippets Manager replied on Mon, 2006/07/03 - 1:30pm

Really? Does this really make a significant difference? If so, any proof?