9 points

Tips for script optimization

Last update May 19, 2009


Here are a few tips to save script execution time.
You can try them with Measure Function Execution Times.
Other articles on JavaScript Optimization can be found here and here.

1) Define variables as you set them.


For example, use figure 1 instead of figure 2:
Figure 1:
var something = 5;
Figure 2:
var something;
something = 5;


2) Lessen your function calls as much as possible.


For example, use figure 3 instead of figure 4:
Figure 3:
var divs = document.getElementsByTagName("div"),
div1 = divs[0],
div2 = divs[1],
div3 = divs[2];
Figure 4:
var div1 = document.getElementsByTagName("div")[0],
div2 = document.getElementsByTagName("div")[1],
div3 = document.getElementsByTagName("div")[2];


3) Use local variables if possible instead of global variables.


Learn more on those terms here.

4) Don't create a variable if you don't need to.


Creating a variable allocates memory (RAM), and is useless when you use the variable once.
It might not look the greatest, but it's faster no doubt.
If you wanted to append a <br> to the body, you would use figure 5 instead of figure 6
Figure 5:
document.body.appendChild(document.createElement("br"));
Figure 6:
var br = document.createElement("br");
document.body.appendChild(br);


5) Use switch instead of if/else for number and string results.


It results in shorter code when it's broken down into assembly.
For example, use figure 7 instead of figure 8:
Figure 7:
var string = "shotgun";
switch(string) {
case "rifle" : var bullets=".30 calibre cartridge";break;
case "shotgun" : var bullets="slug";break;
case "pistol" : var bullets=".222 remington";break;
}
Figure 8:
var string = "shotgun";
if(string=="rifle") {var bullets=".30 calibre cartridge";}
else if(string=="shotgun") {var bullets="slug";}
else if(string=="pistol") {var bullets=".222 remington";}

Scripts mentioned in guide