Main Page

Minimize statement count

In this example, the value
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
var iClientWidth = document.body.clientWidth; = iClientWidth; = 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
statement to define more than one variable at a
time. Further, you can define variables of different types using the same
statement. For instance, the
following code block uses four separate
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 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];
The two preceding statements each have a single purpose: The first retrieves a value from
stores it in
; the second iterates the variable
. 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
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.
Deployment Issues
22_579088 ch19.qxd 3/28/05 11:43 AM Page 591

JavaScript EditorFree JavaScript Editor     Ajax Editor