4 Ways to Speed Up Your Angular App

Monday, November 30, 2015

There are two challenges to managing performance for Angular websites – the time spent performing intensive logic in the client, and the time spent actually rendering content.
When writing an app recently that involved displaying a lot of constantly changing data, I found a few quick wins.

1. Use ‘track by’. The ng-repeat directive is pretty expensive, and if the data changes, you can end up doing a lot of re-calculating and re-rendering. By default Angular will re-draw a DOM node when the  model changes. But if you specify a key to track the model items by, then if the properties of an item change, Angular can update the node without re-drawing the whole thing. This made a really noticeable difference to the speed of my app.


<div ng-repeat="item in items track by item.id">

2. Think about when to use ng-show vs ng-if. If the inital page load involves lots of hidden content that is made visible by a user action, use ng-if. That way, the content isn’t created until it is needed. If a very big complex component is likely to be shown most of the time, it might be more appropriate to use ng-show, to avoid frequent expensive re-rendering.

3. Choose different data structures. This isn’t Angular specific, and might seem obvious, but as someone who was used to writing apps that were fairly low on data, I was very used to just using lots of arrays as data structures, which inevitably resulted in lots of loops in my code. Changing simple arrays to key value lookups allowed me to avoid looping through long lists to get at objects I wanted.

4. Don’t use a sledgehammer to knock in a nail. Angular has some handy utilities, but sometime speed and ease of programming comes at the expense of performance. In a recent app I was collaborating on we found that a frequent call to angular.copy was accounting for 15% of CPU time. In this case, this utility was overkill – we didn’t need an entire deep copy of our object every time, and replacing angular.copy with a simpler custom function made a big difference to page performance.

Leave a Reply

Your email address will not be published. Required fields are marked *