Javascript Performance Optimization

Short Story

Have you ever faced the need to tune the performance of you javascript?

Once upon a time I had an Epic Battle against Javascript Lags in a dashboard app. The app contained a dynamic page with a horrible number of tags (~150k lines of HTML in a generated page).

It was a "bulk CRUD form" page. Actually, a Single Page App (SPA) looking like a monstrous spreadsheet. On initial render it had 10 rows containing 72 html input elements each!

I've tweaked the performance of the javascript code and achieved The Best Code Performance Gain in my career so far :)

IE6 rendering speed was lowered from 60+ seconds to 8 seconds. Some functions were modified to run 400% faster (basically it was achieved by tweaking string concatenation using [].join). A couple of bottlenecks was optimized to run 25 times faster (jQuery references caching).

A Silver Bullet

The common approach here is:

  1. Measure. The golden rule of any optimization. Find the bottleneck first, then optimize.
    In clientside javascript, though, the most probable sources of lags are DOM-tree manipulations and relayout.
  2. Tweak string concatenation in vanilla javascript in older browsers (IE6, IE7. I feel your pain, bro, if you have to maintain this shit). Use [].push and [].join.
  3. Use jQuery wisely and cache the $ references. (Tons of articles available on basic jQuery pitfalls - read em).
  4. Insert the HTML dynamically using documentFragment. Some older browsers (Chrome and IE6,7) may actually work faster with innerHTML batch assignments. Measure it.
  5. If you need to prevent nasty IE6-IE7 alert ("The page seems to run slowly... bla bla bla... should I kill the page?"), you may use setTimeout function to delegate the rendering for the next event-loop cycle. It will free some ticks for other operations and will mimic "asynchronous" execution. This is sufficient to shut IE6 up.
  6. Read about reflows and repaints. Lower the number of those nasty events as much as possible.

Resources

To get some basic knowledge on JS performance optimization read this series of articles.
And here is some v8 specific performance tricks.

Have fun with your JS!