Main Page

Optimize if statements

Optimize if statements
Whenever using
if
statements with multiple
else
statements, make sure you put the most likely condi-
tion first, followed by the second most likely condition, and so forth. For example, if you expect a num-
ber to typically be between 0 and 10, but you have specific functionality for other values, you can
arrange the code like this:
if (iNum > 0 && iNum < 10) {
alert(“Between 0 and 10”);
} else if (iNum > 9 && iNum < 20) {
alert(“Between 10 and 20”);
} else if (iNum > 19 && iNum < 30) {
alert(“Between 20 and 30”);
} else {
alert(“Less than or equal to 0 or greater than or equal to 30”);
}
By always placing the most common conditions first, you can avoid running through multiple false con-
ditions before getting to the true condition.
You should also try to minimize the number of
else if
statements and arrange the conditions so that
they proceed in a binary search fashion. The previous example, for instance, can be rewritten this way:
if (iNum > 0) {
if (iNum < 10) {
alert(“Between 0 and 10”);
} else {
if (iNum < 20) {
alert(“Between 10 and 20”);
} else {
if (iNum < 30) {
alert(“Between 20 and 30”);
} else {
alert(“Greater than or equal to 30”);
}
}
}
} else {
alert(“Less than or equal to 0”);
}
This may look complicated, but it’s more in line with how the underlying (interpreted) code is executed
and so can result in faster execution. Always try to have a branch where the
if
condition tests if a value
is greater than, less than, or equal another value; then let an
else
statement handle the other possibility.
Switch versus If
The classic question of whether to use a
switch
statement or an
if
statement applies to JavaScript as
well. Generally speaking, anytime you have more than two conditions to test for, it’s best to use a
switch
statement whenever possible. Often, using the
switch
statement instead of an
if
statement can
result in execution that is up to 10 times faster. This is even easier to take advantage of in JavaScript
because you can use any type of value in a
case
statement.
589
Deployment Issues
22_579088 ch19.qxd 3/28/05 11:43 AM Page 589


JavaScript EditorFree JavaScript Editor     Ajax Editor


©