Client side JavaScript optimization techniques
Thanks to everyone that attended the December DevCares event in Chicago last week. One of the topics I presented on was techniques for optimizing client side JavaScript to obtain a better Rich Interactive Internet Application (RIIA) experience. A lot of you gave me feedback that you found the content informative and I wanted to pass along a blog link that contains most of the topics we covered so you can have it for future reference:
http://blogs.msdn.com/ie/archive/2006/11/16/ie-javascript-performance-recommendations-part-2-javascript-code-inefficiencies.aspx
Keep the following points in mind as well when writing your script code to maximize your performance:
Performance implications can be tied to the lookup in the scope chain for the variables you are accessing. Here is the list of scope in order of least to highest performance impact: Local variables, global variables, DOM. The DOM is the most expensive operation you can do so be sure to evaluate whenever you are going to walk the tree to work on an object. If you need access to an object in the tree for multiple operations consider using a pointer so that your code doesn't walk the tree each time and take the performance hit. Example:
var lside = document.body.all.lside.value;
var rside = document.body.all.rside.value;
can be changed to:
var ptrAll = document.body.all;
var lside = ptrAll.lside.value;
var rside = ptrAll.rside.value;
Also, you can use function pointers to reduce the overhead of looking up the entry point in situations where the function may be called numerous times.
var length = myCollection.getItemCount();
for (var idx=0; idx<length; idx++){
Work(myCollection[idx]);
}
The above loop will perform symbol resolution for the location of the Work function every iteration of the loop, which depending on the collection could be a large iteration. The following example utilizes a function pointer to perform the symbol resolution once prior to the loop.
var funcWork = Work;
var length = myCollection.getItemCount();
for (var idx=0; idx<length; idx++){
funcWork(myCollection[idx]);
}
Look for more great developer tips, examples and overviews coming in the 2008 DevCares sessions!