Why is iterating through an array backwards faster than forwards Why is iterating through an array backwards faster than forwards javascript javascript

Why is iterating through an array backwards faster than forwards


Because your forwards-condition has to receive the length property of your array each time, whilst the other condition only has to check for "greater then zero", a very fast task.

When your array length doesn't change during the loop, and you really look at ns-perfomance, you can use

for (var i=0, l=arr.length; i<l; i++)

BTW: Instead of for (var i = arr.length; i > 0; --i) you might use for (var i = arr.length; i-- > 0; ) which really runs through your array from n-1 to 0, not from n to 1.


Because in the first form you are accessing the property length of the array arr once for every iteration, whereas in the second you only do it once.


If you want to have them at same pace, you can do that for forward iteration;

for(var i=0, c=arr.length; i<c; i++){}

So, your script won't need to take length of array on everystep.