Table of Contents
Angular is, by default, a fast and performant framework. While it leaves ample space for improvement by opting out some of its magic, we almost never have to do anything special to write extremely performant code for the average app.
With that said, some difficulties will eventually arise when we are writing either performance-critical apps, apps with large and complex content, or apps updated extremely frequently.
There are loads of resources and popular advice out there about improving performance with Angular apps. While most of it is totally good and valid advice, what I have personally found while mitigating performance issues is not often talked about.
In this article, I want to show some of the most important reasons why Angular apps become slow at scale. What we will see is that it doesn’t really matter the framework used — these tips will be valid for any framework.
App is rendering too often
Let’s start with this quite common issue: your application re-renders components unnecessarily, making your application slower than it could be. This is both easy to solve and easy to cause.
We can solve this by doing
- Use OnPush Change Detection Strategy
Setting the default change detection to OnPush is an almost mandatory step if your application is suffering from slow performance, or if you want to prevent from it happening in the future.
By setting your components to update only “on push”, you prevent re-rendering components that don’t need to be checked.
- Use Async Pipe
asyncpipe subscribes to an
Promiseand returns the latest value it has emitted. When a new value is emitted, the
asyncpipe marks the component to be checked for changes. When the component gets destroyed, the
asyncpipe unsubscribes automatically to avoid potential memory leaks.
Preventing observable from emitting is a good way to prevent your component from re-rendering. For example, you may use operators such as
distinctUntilChangedto skip re-renderings altogether.
This is a use-case where Angular doesn’t excel at, and it is probably due to Zone.js, which is also the reason behind Angular’s magical change detection.
Zone.js will monkey-patch all events and will schedule a change detection when any of these happened. That means that if your application is streaming events at a fast rate (Web-socket, or even DOM events), for each event received, Zone will trigger a change detection. There’s definitely room for improvements in similar cases.
Of course, we can't remove Zone from our Angular app to solve this issue. Here are a few steps we can take instead:
- Detach the affected components, then update surgically when your subscriptions get notified
ngZone.runOutsideAngular(callback)to run the callback outside of Angular’s change detection
- last resort: exclude the event from being monkey-patched by Zone
Your app is rendering too much
No matter how fast your framework is, if you are rendering thousands of complex components in one go, the browser is eventually going to show some amount of lag.
Maybe this isn’t very noticeable in powerful machine, slower machines will definitely get trouble. Might be chance that every user doesn't have powerful machine.
It’s extremely important to make sure that components rendered many items (eg. within lists) are optimised in a particular way.
We can solve this by doing
- Virtual Scrolling
Only render what the user can see.
While this has accessibility/usability implications to be aware of, it is one of the best methods to improve perceived performance and avoid getting the page frozen for an unreasonable amount of time.
It’s pretty easy to implement: the Angular CDK provides a utility for this!
- Async Rendering
The concept is like suppose you have large amount of items to be displayed then start rendering a limited number of items (ex, 50 out of 500), then schedule a subsequent rendering with the next 50 items until all items are rendered.
- Lazy Rendering
Not everything has to be rendered right away, sometimes we can simply render a component when the user needs to interact with it.
In this case we can use Angular lazy loading concept.
- Lazy Listeners
Subscribing and listening to too many events may be quite expensive. Avoiding subscribing to too many events can be done in different ways:
- If you have a large list of items with DOM handlers, make sure you only subscribe to the items that are visible (virtual scrolling help with this)
- Sometimes you may want to only create one single global event from within a Service, rather than subscribing to the event in each Directive/Component
Some code… is just slow
If you’ve done your research and figured out that your app doesn’t render that much and doesn’t render that often, then your code may just simply be quite slow. This is probably due to some heavy scripting and not DOM-related.
We can solve this by doing
- Use WebWorkers. The Angular CLI also provides a command to generate a WebWorker in a snap. When is this a suitable route? Simple — when your code has nothing to do with rendering and takes a while to execute.
- Use WebAssembly, for example using AssemblyScript. Read this case study from Figma for more information.
If above solutions doesn't resolve your use case then you can do following things to can improve your runtime performance.
- Use a Custom Iterable Differ
- Turn everything into for-loops, scrap
continueto reduce the number of iterations.
- Opt-out of the framework’s magic: make sure you use ChangeDetection.OnPush and TrackBy for arrays
- Render less often by surgically triggering change detection on your components. Run outside Zone when needed.
- Try to render less using a variety of techniques such as virtual scrolling and lazy rendering
- Don’t listen to everything: subscribe to only the items that are visible, and subscribe to only one global event listener
These are the reasons and it's solution about Angular Application Performance.