One of the advantages when working with AngularJS is the two-way-data-binding. Internally assessed AngularJS checks references to
One of the advantages when working with AngularJS is the two-way-data-binding. Internally, assessed AngularJS checks references to objects in the scope during each cycle of $digest for changes and update the corresponding view.
Let’s see how this process is affected by the size of the lists we use and the amount of watchers assigned to them, and how the use of immutable lists can improve the performance of these.
What happens internally?
If, for example, we have in our view a ng-repeat referring to a list and add an item to this list, AngularJS will first compare this list by its reference to detect if it was changed by another list. If it was not, it will compare each element until it finds a new added element and it is updated as appropriate. It is easy to see how the amount of assessments that AngularJS makes depends on the size of the list, and the number of watchers assigned to them (for example, we can have a ng-repeat referring to a list, a directive and that it also uses the same code in the controller, explicitly doing a $scope.$watch() on it).
Immutable lists
An alternative to avoid the impact on performance is to use immutable lists. The idea is simple: because it’s immutable, when a change is made, the original list remains intact and returns a new one with the changes made. For that, there’s a library called Immutable.js. For example:
var list = Immutable.List([1, 2, 3]); var changed = list.push(4); list.toString(); // List [ 1, 2, 3 ] changed.toString(); // List [ 1, 2, 3, 4 ] list === changed // false
Where does this affect AngularJS? If we use immutable lists when we make a change in them, a new list will be generated, and when running the $digest, AngularJS will detect that the reference to the list has changed and will updated the view without evaluating each element of it.
angular-immutable
To integrate Immutable.js with AngularJS, there is a directive called angular-immutable used as follows:
var app = angular.module('sampleApp', ['immutable']) .controller('SampleCtrl', function($scope){ $scope.list = Immutable.List([1, 2, 3]); });
<body ng-app="sampleApp" ng-controller="SampleCtrl"> <ul> <li immutable="list" ng-repeat="item in list" ng-bind="item"></li> </ul> </body>
The mutable attribute list indicates that the list “list” is immutable.
What are the effects on performance when using Immutable? For a list of 10,000 elements:
We see that the greater the number of bindings “listening” to the list (x-axis), most notorious is the gain in performance.
We also see that the performance gets worse for fewer bindings. The same happens if we need to modify our lists frequently.
Source: Boost the Performance of an AngularJS Application Using Immutable Data