Is
for (var i=0, cols=columns.length; i<cols; i++) { ... }
more efficient than
for (var i=0; i<columns.length; i++) { ... }
?
In the second variant, is columns.length calculated each time the condition i<columns.length is checked ?
Is
for (var i=0, cols=columns.length; i<cols; i++) { ... }
more efficient than
for (var i=0; i<columns.length; i++) { ... }
?
In the second variant, is columns.length calculated each time the condition i<columns.length is checked ?
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)
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).
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.sun.com/greimer/resource/loop-test.html
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