tomasdev

web development handcrafted

JavaScript performance optimization notes

6 Jan, 2012. Written by Tom Roggero

I was asked to help in a performance issue on a website with a table containing 40.000 DOM objects inside of it, and with tools to filter that content. After researching and backing up some links I had, I decided to make this list:

  1. Try to investigate and see what is inside the plugin you are using. Not only to check for errors or performance penalties but also to know how things work.
  2. When using a framework selection method (such as jQuery $(".something") or ExtJS .select(".something")), reduce the scope of DOM objects search by adding a parent ID.
  3. Prevent using html comment nodes
  4. Whenever possible, save the selected parsed objects (i.e., Ext.select("selector") or $("selector")) as a single variable such as $selectorName (I use $ to differentiate jQuery versus DOM objects). That will save it in memory (cache) and won't look up the DOM again for the same item. In addition, try to make that variable global if object is ready (such as for document or window objects). Even if object is just used twice.
  5. Define local variables for window, document, and some other global elements (Same concept applies to renaming this to self).
  6. Change CSS classes not styles.
  7. Try to use as less DOM append & remove as possible.
  8. If you constantly reference foo.bar you can get a performance boost by defining var bar = foo.bar
  9. Avoid as many for-in loops as you can
  10. Use native for instead of framework .each
  11. Implement memoization for "always same results" (a function that returns same thing always for given parameters). Example: filtering a table could take advantage memoization.
  12. If you have a lot of elements to be inserted into the DOM, surround them with a parent element for better performance.
  13. Don't use string concatenation, instead use array's join() method for a very long strings.

Sources: Tuts+, jQuery howto, ifadey, Jon Raasch, Addy Osmani, AwesomeKling

I think most of them might be applied kind of easily. Some others, such as memoization could be harder when you have tons of code (such as 3000 lines libraries).

Some guidelines about coding best practices:

Want to measure JS performance? Go to JSPERF and create your test! It also let's you measure asynchronous stuff.

Related posts /

Leave a Reply