Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is i-- faster than i++ in loops? [duplicate]

I've heard this quite a few times. Are JavaScript loops really faster when counting backward? If so, why? I've seen a few test suite examples showing that reversed loops are quicker, but I can't find any explanation as to why!

I'm assuming it's because the loop no longer has to evaluate a property each time it checks to see if it's finished and it just checks against the final numeric value.

I.e.

for (var i = count - 1; i >= 0; i--) {   // count is only evaluated once and then the comparison is always on 0. } 
like image 293
djdd87 Avatar asked Aug 27 '09 11:08

djdd87


People also ask

Why can ++ i be faster than i ++?

Why is ++i faster than i++ in C++? I've heard this question come up a few times in C++ programming circles, “Why is ++i faster/better than i++?” The short answer is: i++ has to make a copy of the object and ++i does not. The long answer involves some code examples.

Is ++ i or i ++ more efficient?

According to the Google C++ Style Guide, "when the return value is ignored, the 'pre' form ( ++i ) is never less efficient than the 'post' form ( i++ ), and is often more efficient."

Is ++ i faster than i ++ in for loops in Java?

No there will be no difference at all.

Is decrementing faster than incrementing?

Increment is always faster than decrement.


1 Answers

It's not that i-- is faster than i++. Actually, they're both equally fast.

What takes time in ascending loops is evaluating, for each i, the size of your array. In this loop:

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

You evaluate .length only once, when you declare i, whereas for this loop

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

you evaluate .length each time you increment i, when you check if i <= array.length.

In most cases you shouldn't even worry about this kind of optimization.

like image 176
alestanis Avatar answered Oct 25 '22 12:10

alestanis