Writing Robust AngularJS Web Applications
A given watchExpression is executed at least once (usually
twice) in each and every turn of the $digest loop. It is possible to
slow down the entire AngularJS application by introducing a watch
expression that requires significant time to execute. We need to pay
special attention to the watch-expression part of a watcher, and avoid
introducing expensive computations in this part.
Ideally the watch-expression part of a watcher should be as simple as possible
and execute as fast as possible. There are a number of anti-patterns that should be
avoided in order to have watch-expression executing fast.
Firstly, we should minimize expensive computations in a watch-expression.
Usually we use simple expressions in templates, which results in fast to execute
watch-expressions, but there are two situations where it is easy to introduce
non-trivial computations.
You should pay special attention to expressions that execute functions, for example:
{{myComplexComputation()}}
As those will result in the myComplexComputation() being part of the watch-
expression! Another non-obvious consequence of using functions is that we can
accidently leave some logging statements in them. It turns out that writing to
console.log slows down a watcher considerably. Let's consider two functions:
$scope.getName = function () {
return $scope.name;
};
$scope.getNameLog = function () {
console.log('getting name');
return $scope.name;
};
If you observe Batarang's performance tab for the markup shown as follows:
<span>{{getName()}}</span>
<span>{{getNameLog()}}</span>
You will notice a dramatic difference: