Pre-cache your for loops

While reading through the JavaScript Patterns book, I saw an item that totally stuck out as a crystal clear “duuhhh!!” moment.  Why have I never seen/heard of that before and certainly why wasn’t I doing it regularly (and why hadn’t I thought of it to be honest).

Instead of doing this:

for(var i=0; i < $('someselector li').length; i++){
     //loop through each LI in a UL, or any collection
     //do work...
}

Pre-cache the length instead, so you arent making extra calls to jQuery every time to have the length computed (for every cycle in the for loop!):

for(var i=0, var max=$('someselector li').length; i < max; i+=1){
     //loop through each LI in a UL, or any collection
     //do work...
}

As long as you aren’t actually messing with the items in the collection which would cause length to change, this method works perfectly fine and only does the extra work of computing length (max) once! (Also note the use of +=1 instead of ++ – JSLint prefers it this way.)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s