HTML and CSS Reference
In-Depth Information
Figure 12-18
summary methods for arrays (continued)
Method
Description
reduceRight( function )
Reduces the array from the last element by passing the original array
items to function , keeping only those elements that return a value
of true
some( function )
Tests whether the condition expressed in function holds for any ele-
ments in the array ( true ) or for no elements in the array ( false )
Decision Making: Efficient Loops
As your programs increase in size and complexity, the ability to write efficient code
becomes essential. Bloated, inefficient code is particularly noticeable with program loops
that might repeat the same set of commands hundreds or thousands of times. A millisec-
ond wasted due to one poorly written command can mean an overall loss of dozens of
seconds when it is part of a loop. Because studies show that users will rarely wait more than
a few seconds for program results, it's important to shave off as many milliseconds as you
can. Here are some ways to speed up your loops:
• Calculate outside the loop. There is no reason to repeat the exact same calculation hun-
dreds of times within a loop. For example, the following code unnecessarily recalculates
the same Math.log(i+1) value a thousand times in the nested for loop:
for (i = 0; i < 1000; i++) {
for (j = 0; j < 1000; j++) {
table[i][j] = j*Math.log(i+1);
}
}
Instead, place that calculation outside of the nested loop, where it will be calculated
only once:
for (i = 0; i < 1000; i++) {
var x = Math.log(i+1);
for (j = 0; j < 1000; j++) {
table[i][j] = j*x
}
}
• Determine array lengths once. Rather than forcing JavaScript to count up the length of
a large array each time through the loop, calculate the length before the loop starts:
var x = myArray.length;
for (var i = 0; i < x; i++) {
commands
}
• Decrement rather than increment. Instead of counting up to an array length, count
down from the array length to 0, as in the following for loop:
var x = myArray.length;
for (var i = x; i--) {
commands
}
When the counter variable equals 0, the loop will stop.
• Unroll the loop. When only a few items are being iterated in a loop, it's actually faster
not to use a program loop. Enter each counter value explicitly in separate statements.
Finally, a long command block is a red flag warning you that you might be trying to do too
much each time through a loop. Look for ways to reduce the number of tasks and calcula-
tions in the command block to a bare minimum.
Search WWH ::

Custom Search