Local Optimization--Part 2 of Chapter 10 from Speed Up Your Site (3/3)--WebReference.com
[previous] |
Speed Up Your Site, Chapter 10: Optimizing JavaScript for Execution Speed
Use Local versus Global Variables
Reducing the scope of your variables is not only good programming practice, it is faster. So instead of this (see Listing 10.7):
Listing 10.7 Loop with Global Variable
function MyInnerLoop(){
for(i=0;i<1000;i++);
}
Do this (see Listing 10.8):
Listing 10.8 Loop with Local Variable
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 https://javascript-games.org/articles/local_global_bench.html.
Trade Time for Space
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
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
Interpreters reduce program space requirements by replacing common sequences with more compact representations.
Some 5K competitors (https://www.the5k.org/) combine these two techniques to create self-extracting archives of their JavaScript pages, trading startup speed for smaller file sizes (https://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.]
[previous] |
Created: January 15, 2003
Revised: January 15, 2003
URL: https://webreference.com/programming/optimize/speedup/chap10/2/3.html