Why is iterating through an array backwards faster than forwards
JavascriptPerformanceOptimizationJavascript Problem Overview
Given this code:
var arr = [];
for (var i = 0; i < 10000; ++i)
arr.push(1);
Forwards
for (var i = 0; i < arr.length; ++i) {}
Backwards
for (var i = arr.length - 1; i >= 0; --i) {}
Hard-coded Forward
for (var i = 0; i < 10000; ++i) {}
Why is backwards so much faster?
Here is the test: http://jsperf.com/array-iteration-direction
Javascript Solutions
Solution 1 - Javascript
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.
Solution 2 - Javascript
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.
Solution 3 - Javascript
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.
Solution 4 - Javascript
I am not entirely sure about this, but here is my guess:
For the following code:
for (var i = 0; i < arr.length; ++i) {;
}
During runtime, there is an arr.length calculation after each loop pass. This may be a trivial operation when it stands alone, but may have an impact when it comes to multiple/huge arrays. Can you try the following:
var numItems = arr.length;
for(var i=0; i< numItems; ++i)
{
}
In the above code, we compute the array length just once, and operate with that computed number, rather than performing the length computation over and over again.
Again, just putting my thoughts out here. Interesting observation indeed!
Solution 5 - Javascript
i > 0
is faster than i < arr.length
and is occurring on each iteration of the loop.
You can mitigate the difference with this:
for (var i = 0, len = arr.length; i < len; ++i) {;
}
This is still not as fast as the backwards item, but faster than your forward option.
Solution 6 - Javascript
And these are equally good:
var arr= [], L= 10000;
while(L>-1) arr[L]= L--;
OR
var arr= [], i= 0;
while(i<10001) arr[i]=i++;
Solution 7 - Javascript
do it like below, it will perform in same way. because arr.length
takes time in each iteration in forward.
int len = arr.length;
forward
for (var i = 0; i < len; ++i) {
}
backward
for (var i = len; i > 0; --i) {
}