Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is iterating through an array backwards faster than forwards

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

like image 351
samccone Avatar asked Dec 31 '11 17:12

samccone


People also ask

Why reverse for loop is faster?

Backwards for loop is faster because the upper-bound (hehe, lower-bound) loop control variable does not have to be defined or fetched from an object; it is a constant zero. There is no real difference. Native loop constructs are always going to be very fast.

Which array method is faster?

In case of multiple iterations of the loop, and where the size of array is too large, for loop is the preference as the fastest method of elements' iteration. While loops perform efficient scaling in case of large arrays.

How do you iterate an array backwards?

To loop through an array backward using the forEach method, we have to reverse the array. To avoid modifying the original array, first create a copy of the array, reverse the copy, and then use forEach on it. The array copy can be done using slicing or ES6 Spread operator.

Are arrays faster than loops?

Array Computations are Faster than For Loops Actually, it is a bad practice in Python to use for loops, list comprehensions, or . apply() in pandas. Instead, you should always prefer array computations. It only took 4.84 seconds!


2 Answers

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.

like image 194
Bergi Avatar answered Sep 21 '22 20:09

Bergi


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.

like image 44
rabusmar Avatar answered Sep 21 '22 20:09

rabusmar