Main Page

Minimize statement count

In this example, the value
document.body.clientWidth
is used twice, but it’s retrieved using named
properties (an expensive operation compared to accessing a single variable). You can rewrite this code to
use a local variable instead of accessing
document.body.clientWidth
twice:
var iClientWidth = document.body.clientWidth;
oDiv1.style.left = iClientWidth;
oDiv2.style.left = iClientWidth;
Note that this example also reduces the algorithmic complexity of the previous code by cutting two calls
to linear algorithms down to one.
Minimize statement count
It stands to reason that the fewer statements a script has, the less time needed for it to execute. You can
minimize the number of statements in JavaScript code in numerous ways when defining variables, deal-
ing with iterating numbers, and using array and object literals.
Define multiple variables
As mentioned earlier in the book, you can use the
var
statement to define more than one variable at a
time. Further, you can define variables of different types using the same
var
statement. For instance, the
following code block uses four separate
var
statements to define four variables:
var iFive = 5;
var sColor = “blue”;
var aValues = [1,2,3];
var oDate = new Date();
These four statements can be rewritten to use a single
var
statement:
var iFive = 5 , sColor = “blue”, aValues = [1,2,3], oDate = new Date();
By eliminating three statements you make this code segment run faster.
Insert iterative values
Any time you are using an iterative value (that is, a value that is being incremented or decremented at
various locations), combine statements whenever possible. Consider the following code snippet:
var sName = aValues[i];
i++;
The two preceding statements each have a single purpose: The first retrieves a value from
aValues
and
stores it in
sName
; the second iterates the variable
i
. These can be combined into a single statement by
inserting the iterative value into the first statement:
var sName = aValues[i++];
This single statement accomplishes the same thing as the previous two statements. Because the incre-
ment operator is postfix, the value of
i
isn’t incremented until after the rest of the statement executes.
Whenever you have a similar situation, try to insert the iterative value into the last statement that uses it.
591
Deployment Issues
22_579088 ch19.qxd 3/28/05 11:43 AM Page 591


JavaScript EditorFree JavaScript Editor     Ajax Editor


©