Alex Rivera | Logout

JavaScript loop performance - Why is to decrement the iterator toward 0 faster than incrementing

Asked 2010-08-19T10:09:31.883
72

In his book Even Faster Web Sites Steve Sounders writes that a simple way to improve the performance of a loop is to decrement the iterator toward 0 rather than incrementing toward the total length (actually the chapter was written by Nicholas C. Zakas). This change can result in savings of up to 50% off the original execution time, depending on the complexity of each iteration. For example:

var values = [1,2,3,4,5];
var length = values.length;

for (var i=length; i--;) {
   process(values[i]);
}

This is nearly identical for the for loop, the do-while loop, and the while loop.

I'm wondering, what's the reason for this? Why is to decrement the iterator so much faster? (I'm interested in the technical background of this and not in benchmarks proving this claim.)


EDIT: At first sight the loop syntax used here looks wrong. There is no length-1 or i>=0, so let's clarify (I was confused too).

Here is the general for loop syntax:

for ([initial-expression]; [condition]; [final-expression])
   statement
  • initial-expression - var i=length

    This variable declaration is evaluated first.

  • condition - i--

    This expression is evaluated before each loop iteration. It will decrement the variable before the first pass through the loop. If this expression evaluates to false the loop ends. In JavaScript is 0 == false so if i finally equals 0 it is interpreted as false and the loop ends.

  • final-expression

    This expression is evaluated at the end of each loop iteration (before the next evaluation of condition). It's

Edit
Report

2 Answers

16

It is easy to say that an iteration can have less instructions. Let’s just compare these two:

for (var i=0; i<length; i++) {
}

for (var i=length; i--;) {
}

When you count each variable access and each operator as one instruction, the former for loop uses 5 instructions (read i, read length, evaluate i<length, test (i<length) == true, increment i) while the latter uses just 3 instructions (read i, test i == true, decrement i). That is a ratio of 5:3.

answered 2010-08-19T10:23:06.340
1

I am not sure if it's faster but one reason i see is that when you iterate over an array of large elements using increment you tend to write:

for(var i = 0; i < array.length; i++) {
 ...
}

You are essentially accessing the length property of the array N (number of elements) times. Whereas when you decrement, you access it only once. That could be a reason.

But you can also write incrementing loop as follows:

for(var i = 0, len = array.length; i < len; i++) {
 ...
}
answered 2010-08-19T10:20:35.460

Your Answer