Javascript Performance Tips
I just found this really great talk on YouTube from a Google Tech Talk called, Speed Up Your JavaScript. It’s a guy from Yahoo named Nicholas Zakas that talks about various things you can do to get better performance in you Javascripts.
Some of the things he talks about is:
Scope management
In this part Nicolas explains the scope chain and shows some statistics on how long it takes to access data in different places in it.
Data Access Performance
It turns out you can gain quite some performance, especially in IE, by thinking about how you access data. By avoiding global variables and object properties/array items and instead use local variables as much as possible you can make your code run faster.
Loops
By doing some really easy modification to your loops you can get a 50% performance boost. What it boils down to is to :
- Decrease amount of work per iteration
- Decrease number of iterations
You should also avoid using For-in loops and for each loops and all the function based loops found in Javscript libraries like jQuery and YUI. These takes up to 8 times longer to run than regular for loops.
DOM
In this part Nicholas, amnong other things, talks about HTMLCollections and how slow they are. The reason being that they are dynamic by nature. For example just looping through an HTMLCollection takes up to 68 times longer (in IE) than it takes to loop through an array. Fortunately he also provides ways to remedy this.
He also describes how to avoid unnecesary reflow of the web page.
The video
This video gave me so much new information on how to optimize my Javascript code. This is definitely the best talk I ever seen on the subject. If you’re at all interested in Javascript you should definitely watch it.