Chapter 11
Performance tuning of AngularJS applications
We would like to have applications that are "fast". But "fast" might mean different
things to different people, and this is why we need to focus on measurable items that
influence the overall performance. In this chapter, we are focusing on the in-browser
performance and putting network-related problems aside (those are discussed in
Chapter 12, Packaging and Deploying AngularJS Web Applications). If we narrow down
performance concerns to what is happening in a browser, we need to look at the CPU
utilization and memory consumption.
Optimizing CPU utilization
Apart from an application's logic there are number of AngularJS-specific operations
that will eat up CPU cycles. The $digest loop requires our special attention. We
need to make sure that individual $digest cycles are fast, and also arrange our code
in a way that AngularJS enters the $digest loop as infrequently as possible.
Speeding up $digest loops
We need to strive to keep the $digest loop execution time under 50 ms so the
human eye can't register its execution time. This is important since our application
will be perceived as responding instantaneously to users' actions (DOM events) if
the $digest loop is unnoticeable.
There are two primary directions we can explore in order to fly under the "50 ms per
$digest cycle" radar:
- Make individual watches faster
- Limit the number of watches evaluated as part of an individual
$digest cycle
Keeping watches slim and fast
If you recall the general syntax of a watch expression:
$scope.$watch(watchExpression, modelChangeCallback)
You will remember that each and every individual watch is composed of two
distinct parts: watchExpression that is used to compare model values, and the
modelChangeCallback that is executed when model mutation is detected. The
watchExpression is executed far more frequently as compared to the callback,
and this is why it is the watchExpression that requires our special attention.