Main Page

Keep these algorithms in mind when trying to optimize your code. Here are a couple basic rules for
using the correct algorithms:
?
Whenever possible, use local variables or numerically indexed arrays instead of named properties.
?
If a named property is going to be used more than once, store its value in a local variable to
avoid running a linear algorithm each time the value is needed.
Loops account for a large amount of processing in most programming languages, so keeping them effi-
cient can greatly decrease execution time. A well-known strategy in programming is to iterate through
loops in reverse, starting at the last item and working back to the first. Here’s a regular
for
loop:
for (var i=0; i < aValues.length; i++) {
//do something here
}
To reverse this, start the iterator (
i
) at the last item in the array, which is in position
aValues.length-1
;
then check to see if
i
greater than or equal to
0
and decrement
i
for (var i=aValues.length-1; i >= 0; i--) {
//do something here
}
Reversing the loop helps by reducing the complexity of algorithms. It uses a constant value (0) as the
control statement for the loop to reduce the execution time.
You can replace
while
loops with
do..while
loops to further decrease execution time. Suppose you
have the following
while
loop:
var i=0;
while (i < aValues.length) {
//do something here
i++;
}
The previous code can be rewritten using a
do..while
loop without changing its behavior:
var i=0;
For further information on Big O Notation and computer science algorithms, please refer
to “Big O Notation” from the Wikipedia, available at
http://en.wikipedia.org/
wiki/Big_O_notation
.
584
Chapter 19
22_579088 ch19.qxd 3/28/05 11:43 AM Page 584

Free JavaScript Editor     Ajax Editor