Main Page

executed

iTestValue = 0;
} while (--iLoopCount > 0);
The variable
iIterations
contains the number of times that the loop that should be executed. The
variable
iLoopCount
contains the number of times it is necessary to repeat the
do..while
loop. The
iTestValue
variable represents which
case
in the
switch
statement should be executed the very first
time the loop is entered; every other time, execution starts with
case 0
and runs through all the rest
(notice that no
break
statements stop execution after a
case
statement is executed). If you apply Duff’s
Device to the previous example, this is the result:
var aValues = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
var iIterations = aValues.length;
var iLoopCount = Math.ceil(iIterations / 8);
var iTestValue = iIterations % 8;
var iSum = 0;
var i = 0;
do {
switch (iTestValue) {
case 0: iSum+= aValues[i++];
case 7: iSum+= aValues[i++];
case 6: iSum+= aValues[i++];
case 5: iSum+= aValues[i++];
case 4: iSum+= aValues[i++];
case 3: iSum+= aValues[i++];
case 2: iSum+= aValues[i++];
case 1: iSum+= aValues[i++];
}
iTestValue = 0;
} while (--iLoopCount > 0);
Notice that
iIterations
has been set to the number of values in the array, and the
iSum
and
i
variables
have been added. The
iSum
variable, of course, holds the result of adding all the numbers in the array; the
i
variable is used as an iterator to move through the array (just as with the
for
and
do..while
loops).
Before the loop is executed,
iLoopCount
is equal to
3
, meaning that the loop is executed three times. The
value of
iTestValue
is equal to
4
, so when execution enters the first loop, it skips down to case 4 in the
switch statement. After those four lines are executed,
iTestValue
is set back to
0
. From that point on,
whenever the loop executes, all cases beginning at
case 0
are executed.
Greenburg further optimized his JavaScript version of Duff’s Device by splitting the single
do..while
loop into two separate loops. The algorithm is as follows:
var iLoopCount = iIterations % 8;
while (iLoopCount--) {
[execute statement]
}
587
Deployment Issues
22_579088 ch19.qxd 3/28/05 11:43 AM Page 587


JavaScript EditorFree JavaScript Editor     Ajax Editor


©