| home / programming / optimize / speedup / chap10 / 2 | [previous] |
|
Reducing the scope of your variables is not only good programming practice, it is faster. So instead of this (see Listing 10.7):
function MyInnerLoop(){
for(i=0;i<1000;i++);
}
Do this (see Listing 10.8):
function MyInnerLoop(){
for(var i=0;i<1000;i++);
}
Local variables are 60 percent to 26 times faster than global variables for tight inner loops. This is due in part to the fact that global variables require more time to search up the function's scope chain. Local variables are properties of the function's call object and are searched first. Netscape 6 in particular is slow in using global variables. Mozilla 1.1 has improved speed, but this technique is relevant to all browsers. See Scott Porter's local versus global test at http://javascript-games.org/articles/local_global_bench.html.
Conversely, you can trade time for space complexity by densely packing your data and code into a more compact form. By recomputing information, you can decrease the space requirements of a program at the cost of increased execution time.
Packing decreases storage and transmission costs by increasing the time to compact and retrieve the data. Sparse arrays and overlaying data into the same space at different times are two examples of packing. Removing spaces and comments are two more examples of packing. Substituting shorter strings for longer ones can also help pack data into a more compact form.
Interpreters reduce program space requirements by replacing common sequences with more compact representations.
Some 5K competitors (http://www.the5k.org/) combine these two techniques to create self-extracting archives of their JavaScript pages, trading startup speed for smaller file sizes (http://www.dithered.com/experiments/compression/). See Chapter 9, "Optimizing JavaScript for Download Speed," for more details.
# # #
[Andy King is the founder and newsletter editor of WebReference.com. The companion Web site for this book can be found at: www.websiteoptimization.com.]
| home / programming / optimize / speedup / chap10 / 2 | [previous] |
From Speed Up Your Site: Web Site Optimization, Chapter 10.
Copyright 2003. Reproduced by permission of New Riders.
Created: January 15, 2003
Revised: January 15, 2003
URL: http://webreference.com/programming/optimize/speedup/chap10/2/3.html