Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
8
rated 0 times [  15] [ 7]  / answers: 1 / hits: 142624  / 15 Years ago, thu, august 27, 2009, 12:00:00

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.
}

More From » performance

 Answers
126

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.


[#98824] Friday, August 21, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sashacitlallik

Total Points: 30
Total Questions: 100
Total Answers: 85

Location: Belarus
Member since Tue, Mar 14, 2023
1 Year ago
;