↑
Main Page
switching
iLoopCount = Math.floor(iIterations / 8);
while (iLoopCount--) {
[execute statement]
[execute statement]
[execute statement]
[execute statement]
[execute statement]
[execute statement]
[execute statement]
[execute statement]
}
The purpose of this algorithm is to account for all the
extra
iterations that must be done (that won’t be
included when the number of iterations is divided by 8) in the first loop. It then continues on into the
second loop to iterate through the multiples of 8 remaining. Applying this algorithm to the previous
example, you get the following:
var iIterations = aValues.length;
var iLoopCount = iIterations % 8;
var iSum = 0;
var i = 0;
while (iLoopCount--) {
iSum += aValues[i++];
}
iLoopCount = Math.floor(iIterations / 8);
while (iLoopCount--) {
iSum += aValues[i++];
iSum += aValues[i++];
iSum += aValues[i++];
iSum += aValues[i++];
iSum += aValues[i++];
iSum += aValues[i++];
iSum += aValues[i++];
iSum += aValues[i++];
}
Once again, a few variables are added to make the example work, but it has the same result as the origi-
nal Duff’s Device port.
Whether to use an algorithm such as Duff’s Device is entirely up to you. You must weigh the cost of
adding extra bytes (increasing download time) against the speed optimization that doing so provides.
Yes, this algorithm can be optimized even further by switching the two
while
loops to
do..while
loops. However, this wasn’t included in Greenburg’s original algorithm.
588
Chapter 19
22_579088 ch19.qxd 3/28/05 11:43 AM Page 588
Free JavaScript Editor
Ajax Editor
©
→