Local Optimization--Part 2 of Chapter 10 from Speed Up Your Site (2/3)--WebReference.com
[previous] [next] |
Speed Up Your Site, Chapter 10: Optimizing JavaScript for Execution Speed
Cache Frequently Used Values
One of the most effective techniques you can use to speed up your JavaScripts is to cache frequently used values. When you cache frequently used expressions and objects, you do not need to recompute them. So instead of this (see Listing 10.5):
Listing 10.5 A Loop That Needs Caching and Fewer Evaluations
var d=35;
for (var i=0; i<1000; i++) {
y += Math.sin(d)*10;
}
Do this (see Listing 10.6):
Listing 10.6 Caching Complex Calculations Out of a Loop
var d=35;
var math_sind = Math.sin(d)*10;
for (var i=0; i<1000; i++) {
y += math_sind;
}
Because Math
is a global object, declaring the math_sind
variable also avoids resolving to a global object for each iteration.
You can combine this technique with minimizing DOM interaction by caching
frequently used object or property references. Simplify the calculations
within your loops and their conditionals.
Store Precomputed Results
For expensive functions (like sin()
), you can precompute values
and store the results. You can use a lookup table (O(1)) to handle any
subsequent function calls instead of recomputing the function (which is
expensive). So instead of this:
function foo(i) {
if (i < 10) {return i * i - i;}
}
Do this:
values = [0*0-0, 1*1-1, 2*2-2, ..., 9*9-9];
function foo(i) {
if (i < 10) {return values[i];}
}
This technique is often used with trigonometric functions for animation purposes. A sine wave makes an excellent approximation of the acceleration and deceleration of a body in motion:
for (var i=1; i<=360; i++) {
sin[i] = Math.sin(i);
}
In JavaScript, this technique is less effective than it is in a compiled language like C. Unchanging values are computed at compile time in C, while in an interpreted language like JavaScript, they are computed at runtime.
[previous] [next] |
Created: January 15, 2003
Revised: January 15, 2003
URL: https://webreference.com/programming/optimize/speedup/chap10/2/2.html