Is
for (var i=0, cols=columns.length; i
more efficient than
for (var i=0; i
Micro optimizations like this don't make huge sense in a language like Javascript unless you have tested and found the loop performance to be an issue.
However, columns.length must be evaluated on each iteration because the number of columns may change during a loop iteration. Therefore storing the loop limit may give slightly better performance (but see my first point).
Yes, it is. Accessing the length property wastes un-needed time (unless the array's length can change during iteration.).
Here is how I loop through arrays: http://gist.github.com/339735
The cached version is faster but, the 2nd version safer.
If you're just curious about which loop types are fastest you may want to check this out: http://blogs.oracle.com/greimer/resource/loop-test.html
Note that most of these loops require an additional statement in the loop to actually retrieve the i'th element from the array. You can avoid that and get a very fast loop with the following variant, which takes advantage of the fact that Javascript just returns undefined (which evaluates to false), if you access an array with an out of bounds index (rather than raising an error):
for (var i = 0, col; col = columns[i]; ++i) { ... }
Obviously this doesn't work if you're iterating through an array which contains elements which would evaluate to false.
Any expression that's in the second portion of a for will be evaluated once per loop.
So, here, with your second proposition, yes, columns.length
will be calculated each time the condition is checked -- which would make the first proposition faster than the second one.
(That's true for many other languages, btw)