-3

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

2

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.