Tuesday, September 1, 2009

Speeding up javascript performance

Hi.

I came across the following video on YouTube by "googletechtalks" in which Nicholas Zakas, the principal front-end designer of Yahoo! homepage presents his finding on what kind of javascript code slows down performance in the various browsers. Kudos to Nicholas for this simple yet thought-provoking presentation. It was an eye-opener into a number of topics I never knew about and has made me think a lot more about any new JS code I write. Here it is:



In my view, the main takeaways from the presentation were:

1. Use local variables in functions for storing out-of-scope variables (in case they are to be used more than once) due to scope chains. Do not use the "with" statement and cautiously use the "catch" phrase of the try-catch blocks. Use closures sparingly due to the same reasons.
2. Data access: Accessing from object property or array item is more expensive. (object prop being most expensive). So store in local variables before using.
3. Decrease number of iterations per loop plus the amount of work being done in each loop.
4. Beware of using HTMLCollection objects (such as those returned from getElementsByTagName) as accessing their properties are very expensive. Store properties in local variables (such as length) or move into a regular object or array before accessing them.
5. Use document fragments (using createDocumentFragment) to update a group of related DOM objects and then update the page to minimize reflows (redraw of pages). Also minimize style changes to prevent reflow.

Cheers.