↑
Main Page
Unroll your loops
do {
//do something here
i++;
} while (i < aValues.length);
This code now runs faster than using the
while
loop, but it can be optimized further by reversing the loop:
var i=aValues.length-1;
do {
//do something here
i--;
} while (i >= 0);
You can also eliminate an extra statement by putting the decrement into the control statement directly:
var i=aValues.length-1;
do {
//do something here
} while (i-- >= 0);
The loop has now been fully optimized for execution speed.
Unroll your loops
Instead of using loops that execute one statement each time through, you can
unroll
these loops to run
multiple statements. Consider the following simple
for
loop:
var aValues = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
var iSum = 0;
for (var i=0; i < aValues.length; i++) {
iSum += aValues[i];
}
This loop body executes 20 times, each time adding to the variable
iSum
. This is a fairly simple opera-
tion, so it’s possible to unroll this operation and execute it several times within the
for
loop:
var aValues = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
var iSum = 0;
for (var i=0; i < aValues.length; i++) {
iSum += aValues[i];
i++;
iSum += aValues[i];
i++;
iSum += aValues[i];
i++;
585
Deployment Issues
22_579088 ch19.qxd 3/28/05 11:43 AM Page 585
Free JavaScript Editor
Ajax Editor
©
→