Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are loops really faster in reverse?

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 267
djdd87 Avatar asked Aug 27 '09 11:08

djdd87


People also ask

Can you go backwards in a for loop?

Let's discuss certain ways in which this can be done. Method #1 : Using reversed() The simplest way to perform this is to use the reversed function for the for loop and the iteration will start occurring from the rear side than the conventional counting.

What is backwards iteration?

This method involves slicing the list which starts from the position -1 and go backwards till the first position. We use a for loop with an iterator used as the index of the element in the list.


2 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 159
alestanis Avatar answered Sep 27 '22 19:09

alestanis


This guy compared a lot of loops in javascript, in a lot of browsers. He also has a test suite so you can run them yourself.

In all cases (unless I missed one in my read) the fastest loop was:

var i = arr.length; //or 10 while(i--) {   //... } 
like image 33
Tom Ritter Avatar answered Sep 27 '22 18:09

Tom Ritter