Tips and Trick to Improve JavaScript Performance

I've recently viewed this awesome video at googletechtalks:

The speaker shows lots of different tips & tricks to improve JavaScript code in order to make it more efficient. Here is the list of those of them that I've found more interesting or that were completely unknown to me:
  • It is importante to narrow the scope of variables. So it is better to use var d = document and then d.whatever, than using document.whateverProperty directly. That is roughly because the more dots.properties you use, the slowest the code.
  • In for or while loops it is better to use reverse looping (i--) and avoid complicated calculations in the conditional sentences. And also avoid that costly sentences get calculated in each cycle of the loop itself.
  • If not estrictly necessary avoid the usage of catch clause to handle errors. So if it is a predictable error figure out another way to deal with it.
  • Reflow is the concept of refreshing the DOM due to changes in the javascript code. The less reflow the better. Therefore, it is better to update the DOM using this: var frag = document.createDocumentFragment(); and adding afterwards the elements needed using frag.appendChild(newElementPreviouslyCreated);.
  • When changing styles it is much better to use .className = "name" referring to a CSS file previously created style, than changing the style in the code itself by code. This also helps to keep separated style, from the code itselft, making the design more robust an clean.
  • And, last but not least, not surprisingly the slowest browser... yes, you get it! IE (either 7 or 8).