Ad

Javascript For Loop Syntax And Performance

- 1 answer

I study javascript with my book recently purchased. And the book explain about the performance of for loop. That is, there are 2 style,

A: for(var i=0; i<arr.length; i++){ //some code... }

B: for(var i=arr.length-1; i>-1; i--){ //some code... }

The book describes "style B is more good performance than A". It seems plausible, but when java(not javascript) syntax I don't care about this situation. So my question is "style B is more effective"? Thank you in advance...

Ad

Answer

In terms of performance, using the decrement operator i-- is not necessarily faster than the increment operator i++. Performance wise, they are both as fast.

The bottleneck has to do with ascending loops. For every number, the size of the array has to be evaluated. Let's take a look at the two cases.

Descending Loop

for (var i = array.length; i >= 1; i-- )

array.length is evaluated only once, upon initialization of the i variable.

Ascending Loop

for (var i = 1; i <= array.length; i++ )

array.length is evaluated every time i is incremented. You also have to check the value of i to make sure it's less than the length of the array.

For further insights, please look at the following blog post

http://www.2ality.com/2013/07/for-loop-performance.html

Ad
source: stackoverflow.com
Ad