Quick AngularJS Optimizations

Jan 22 2015

Here are a few quick tips to optimize AngularJS code for speed:

  • Try to aggregate events by binding at a higher level in the hierarchy (e.g. binding on the container of some elements instead of each individual element), AngularJS makes it all too easy to write ng-clicks inside an ng-repeat of 20,000 elements, not good, a single ng-click on the container, much better.
  • Change ng-style to ng-class – if you don't need to change the style dynamically you should favor ng-class as using ng-styles prevents the browser from applying optimizations at class level.
  • Avoid ng-if in all non-trivial cases – If you have a memory leak (which you don't of course but humor me for a second), ng-if will tend to exacerbate the problem by recreating the culprit over and over again.  Of course fixing the memory leak is another option - if only life were that easy.
  • Cache compiled DOMs instead of using ng-bind-html - using ng-bind-html needlessly runs through static HTML files looking for Angular stuff in each and every digest loop
  • Move angular long expressions to function calls -- yes yes function calls, despite these being watched, parsing these long expressions tend to be more expensive than watches
  • Use display:none on divs that are not currently on the screen – this may save some memory and rendering time in large DOMs
  • When a directive resides inside a repeater try to move as much code as you can to the compile stage – the constructor and link functions run with each iteration, the compile only runs once
  • Try to $watch without the “true” flag where you can – putting “true” in a $watch causes costly comparison in complex objects, consider also using $watchCollection for complex objects instead of $watch + true.
  • Bind once where you can

Go fast!

Gil M.
Software Developer
Back to Blog