Misha Moroshko
Misha Moroshko

Reputation: 171459

Javascript for loop efficiency

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 ?

Upvotes: 13

Views: 3646

Answers (5)

Ming-Tang
Ming-Tang

Reputation: 17661

Yes, it is. Accessing the length property wastes un-needed time (unless the array's length can change during iteration.).

Upvotes: 0

user324312
user324312

Reputation:

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

Upvotes: 4

Simon
Simon

Reputation: 11

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.

Upvotes: 1

Ash
Ash

Reputation: 62145

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).

Upvotes: 5

Pascal MARTIN
Pascal MARTIN

Reputation: 401182

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)

Upvotes: 8

Related Questions