Zakas’ JavaScript performance tips

Nicholad Zakas, who wrote this book, recently spoke about JavaScript performance at Google; his presentation was called “Speed Up Your JavaScript” and it’s available to view on Youtube.

In the presentation Nicholas covers areas rarely talked about; he takes a low-level approach by explaining what’s happening behind the scenes when you do something as simple as creating or requesting a variable in JavaScript. It’s not all conjecture though; he has a number of graphs comparing performance across browsers and then details the steps you can take to optimise your code, in order to protect yourself from less-than-satisfactory JavaScript implementations (IE comes to mind).

I’m not obsessed about performance by any means but I do think that the practices shared in his presentation should be followed to the letter. Speed and performance are hot topics on the client-side; our users demand fast and responsive applications/websites.

His advice:

Five key points emerged during the presentation:

Store out-of-scope variables in local variables.

Minimise property access.

Do as little as possible on each iteration of a loop.

Minimise document reflow by only changing the DOM when absolutely necessary.

Don’t use inline styles unless you’re animating.

Store out-of-scope variables in local variables

The idea behind this technique is to minimise the amount of work required to get at the variable you want. The further away it is (in the scope chain) the longer it’s going to take to retrieve it. The performance cost is normally marginal but it’s still a good practice. Here’s an example:

With each new scope you’re getting further and further away from the global scope, so it makes sense to create local variables pointing to global variables (or any variable higher up in the scope chain). Note that this is only worth doing if you’re going to be referencing the higher variable more than once in the current scope.

Minimize property access

This is quite an obvious one; when you’re going to be retrieving a property more than once you should assign its value to a local variable. For example, caching a method deepely embedded in an object:

Do as little as possible on each iteration of a loop

Loops are the first thing people consider when on the topic of performance. There are a few steps you should take to speed up any given loop. First, if at all possible, use a reverse loop; doing so means you can combine the control condition and any control variable changes:

/* Forward loop */var i =0;
while ( i < length ){
i++;}/* Reverse loop (faster) */var i = length;
while (i--){/* No need to increment; it's already been done in the control condition */}

If you can’t use a reverse loop then make sure to do as little as you can get away with on each iteration. Always cache the length property! If you’re concerned about performance then don’t use iteration-abstractions like jQuery’s each or ECMA-262-5’s Array.forEach().

Minimise document reflow by only changing the DOM when absolutely necessary

I found this particularly interesting; whenever you change the DOM, in any way, the document is “reflowed” (i.e. the browser re-draws it). This is something you want to avoid. As an example, if you want to change a bunch of things within a table you should first remove that table from the DOM (using parentElement.removeChild), make your changes, and then place it back in the DOM. You can retain a reference to its original previous sibling or parent in order to place it back in the same position:

I’m not advocating a new <style> tag for every new style – it’s just an example.

Another useful technique is to build DOM structures outside of the DOM and then to insert them as one document fragment.

Don’t use inline styles unless you’re animating

This is really an extension of the last point; minimising document reflows. Instead of applying several styles to many elements just apply a class that’s already defined somewhere in your CSS. Ideally inline styles should only be used for animating or for small simple changes.

Amy Hoy (rails dev @ slash7) & Thomas Fuchs (scriptaculous) are writing an e-book on JavaScript performance (it currently stands at some 282 pages) that should be in full release soon, she has a discount of $5 (and says she’s likely to put the full-price up after release – because $29 is a bargain for that much material) so grab it asap @ jsrocks.com

I’m glad you enjoyed the presentation. I have a large amount of performance-related posts on my site that I hope you’ll check out as well. And one last point: I’m finishing up a book strictly on JavaScript performance that covers all of my best practices and more.

I personally found it very detailed and definitely worth the price, but depending on your skill level you may not need it (although it was so detailed and covered so much ground – not just code optimization – that I think even hardened JavaScript will get something out of it).

Thanks! I subscribed to your blog some time ago for some reason that I forget. If I hadn’t, I wouldn’t have seen this Google Tech Talk video you posted. I’m so glad that I DID see it! I was able have one more go at optimizing this horrible in-house form I have, and I shaved off about 4 more seconds from the initialization.

Sorry for bumping an older post, but if you do `var jQuery = jQuery;` you’ll find that jQuery === undefined, because you’ve now scoped jQuery to your function, initialized with undefined first, then it gets assigned to jQuery, which is already undefined. You should do `var $ = jQuery;`, or another different name. Or even better, import it in the function arguments:

(function (jQuery) {…}(jQuery));

Anyways, otherwise good concise tips! And, obviously thanks to Zakas too! Sad to get an email from Amazon this morning that my pre-order of your book is getting pushed back to April