Using ng-repeat
in views generally results in poor performance, particularly when there are nested ng-repeat
's.
This is super slow!
<div ng-repeat="user in userCollection">
<div ng-repeat="details in user">
{{details}}
</div>
</div>
Try to avoid nested repeats as much as possible. One way to improve the performance of ng-repeat
is to use track by $index
(or some other id field). By default, ng-repeat
tracks the whole object. With track by
, Angular watches the object only by the $index
or object id.
<div ng-repeat="user in userCollection track by $index">
{{user.data}}
</div>
Use other approaches like pagination, virtual scrolls, infinite scrolls or limitTo: begin whenever possible to avoid iterating over large collections.
Angular has bidirectional data binding. It comes with a cost of being slow if used too much.
Slower Performance
<!-- Default data binding has a performance cost -->
<div>{{ my.data }}</div>
Faster Performance (AngularJS >= 1.3)
<!-- Bind once is much faster -->
<div>{{ ::my.data }}</div>
<div ng-bind="::my.data"></div>
<!-- Use single binding notation in ng-repeat where only list display is needed -->
<div ng-repeat="user in ::userCollection">
{{::user.data}}
</div>
Using the "bind once" notation tells Angular to wait for the value to stabilize after the first series of digest cycles. Angular will use that value in the DOM, then remove all watchers so that it becomes a static value and is no longer bound to the model.
The {{}}
is much slower.
This ng-bind
is a directive and will place a watcher on the passed variable. So the ng-bind
will only apply, when the passed value does actually change.
The brackets on the other hand will be dirty checked and refreshed in every $digest
, even if it's not necessary.
AngularJS has a digest loop. All your functions are in a view and filters are executed every time the digest cycle runs. The digest loop will be executed whenever the model is updated and it can slow down your app (filter can be hit multiple times before the page is loaded).
Avoid this:
<div ng-controller="bigCalulations as calc">
<p>{{calc.calculateMe()}}</p>
<p>{{calc.data | heavyFilter}}</p>
</div>
Better approach
<div ng-controller="bigCalulations as calc">
<p>{{calc.preCalculatedValue}}</p>
<p>{{calc.data | lightFilter}}</p>
</div>
Where the controller can be:
app.controller('bigCalulations', function(valueService) {
// bad, because this is called in every digest loop
this.calculateMe = function() {
var t = 0;
for(i = 0; i < 1000; i++) {
t += i;
}
return t;
}
// good, because this is executed just once and logic is separated in service to keep the controller light
this.preCalulatedValue = valueService.valueCalculation(); // returns 499500
});
Watchers tremendously drop performance. With more watchers, the digest loop will take longer and the UI will slow down. If the watcher detects change, it will kick off the digest loop and re-render the view.
There are three ways to do manual watching for variable changes in Angular.
$watch()
- watches for value changes
$watchCollection()
- watches for changes in collection (watches more than regular $watch
)
$watch(..., true)
- Avoid this as much as possible, it will perform "deep watch" and will decline the performance (watches more than watchCollection
)
Note that if you are binding variables in the view you are creating new watches - use {{::variable}}
to prevent creating a watch, especially in loops.
As a result you need to track how many watchers you are using. You can count the watchers with this script (credit to @Words Like Jared Number of watchers)
(function() {
var root = angular.element(document.getElementsByTagName('body')),
watchers = [],
f = function(element) {
angular.forEach(['$scope', '$isolateScope'], function(scopeProperty) {
if(element.data() && element.data().hasOwnProperty(scopeProperty)) {
angular.forEach(element.data()[scopeProperty].$$watchers, function(watcher) {
watchers.push(watcher);
});
}
});
angular.forEach(element.children(), function(childElement) {
f(angular.element(childElement));
});
};
f(root);
// Remove duplicate watchers
var watchersWithoutDuplicates = [];
angular.forEach(watchers, function(item) {
if(watchersWithoutDuplicates.indexOf(item) < 0) {
watchersWithoutDuplicates.push(item);
}
});
console.log(watchersWithoutDuplicates.length);
})();
These functions are very similar in behavior. ng-if
removes elements from the DOM while ng-show
only hides the elements but keeps all handlers. If you have parts of the code you do not want to show, use ng-if
.
It depends on the type of usage, but often one is more suitable than the other.
If the element is not needed, use ng-if
To quickly toggle on/off, use ng-show/ng-hide
<div ng-repeat="user in userCollection">
<p ng-if="user.hasTreeLegs">I am special<!-- some complicated DOM --></p>
<p ng-show="user.hasSubscribed">I am awesome<!-- switch this setting on and off --></p>
</div>
If in doubt - use ng-if
and test!
By default, bind directives and scopes leave extra classes and markup in the code to assist with various debugging tools. Disabling this option means that you no longer render these various elements during the digest cycle.
angular.module('exampleApp', []).config(['$compileProvider', function ($compileProvider) {
$compileProvider.debugInfoEnabled(false);
}]);
Dependency Injection is a software design pattern in which an object is given its dependencies, rather than the object creating them itself. It is about removing the hard-coded dependencies and making it possible to change them whenever needed.
You might wonder about the performance cost associated with such string parsing of all injectable functions. Angular takes care of this by caching the $inject property after the first time. So this doesn’t happen everytime a function needs to be invoked.
PRO TIP: If you are looking for the approach with the best performance, go with the $inject property annotation approach. This approach entirely avoids the function definition parsing because this logic is wrapped within the following check in the annotate function: if (!($inject = fn.$inject)). If $inject is already available, no parsing required!
var app = angular.module('DemoApp', []);
var DemoController = function (s, h) {
h.get('https://api.github.com/users/angular/repos').success(function (repos) {
s.repos = repos;
});
}
// $inject property annotation
DemoController['$inject'] = ['$scope', '$http'];
app.controller('DemoController', DemoController);
PRO TIP 2: You can add an ng-strict-di
directive on the same element as ng-app
to opt into strict DI mode which will throw an error whenever a service tries to use implicit annotations. Example:
<html ng-app="DemoApp" ng-strict-di>
Or if you use manual bootstrapping:
angular.bootstrap(document, ['DemoApp'], {
strictDi: true
});