Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
159
rated 0 times [  163] [ 4]  / answers: 1 / hits: 53528  / 13 Years ago, sat, december 31, 2011, 12:00:00

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


More From » performance

 Answers
4

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.


[#88298] Thursday, December 29, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hallie

Total Points: 503
Total Questions: 114
Total Answers: 103

Location: Iraq
Member since Fri, Jun 5, 2020
4 Years ago
;