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 6Figure 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";}

login to vote
joe-- we tested "
with" and it doesn't save time :/login to vote
you might want to add that regular expression is in general faster (and way easier) than indexOf and substring
login to vote
Array.forEach();is the fastest way to loop through a array.login to vote
@Avg: RegEx is definitely not faster than indexOf.
Check my Official Time Tests thread. I prove this. You can try it yourself.
@TimSmart: That may be, but I didn't say for() was the fastest, I just encouraged them to count down instead of up if they use a for() loop.
login to vote
their gonna include just-in-time compiling in future firefox versions like java!
that'd be awesome :)
login to vote
I invite all of you to take a look at my looping results.
login to vote
For optimization:
try to avoid "getComputedStyle()"
login to vote
I can't imagine a situation in which you would even use
getComputedStyle(). I would just use something likeelement.style.coloror another workaround if that didn't work in rare occasions.