Is there a config option to lower the amount of AngularJS 1.x digest cycles?

466 Views Asked by At

I was contemplating a means to increase performance in an app while meeting client demands. Right now it seems that the digest runs 5x per second where we only really need it to run perhaps twice per second.

Is there a way to lower the amount of times the digest runs?

2

There are 2 best solutions below

1
chinmayan On BEST ANSWER

In AngularJS there are a set of scenarios when a digest cycle kicks in, some of them are, whenever a value bind to the $Scope or $rootScope object changes(like $scope.text or $rootScope.text), DOM Events (like ng-click, ng-bind etc..), Ajax with callbacks ($http etc..), Timers with callbacks ($timeout, setTimeout etc..), calling $apply, $digest etc..

PFA: enter image description here

To do:

If you want to reduce the number of digest cycles triggered you'll have to look into each of these above-listed points. Like you can reduce the number of $watchers by using one-time binding (eg: {{::myProperty}} - documentation), limiting the cases of programmatically triggering $apply ($scope.$apply), and replacing $timeouts with $scope.$evalAsync() (because $scope.$evalAsync() will try to trigger in the same digest loop itself whereas $timeout() will wait for the current digest cycle to be done) or un registering the watchers once you found the change and no longer required to watch again like this,

var unregister = $scope.$watch('foo', function () {
// Do something here ...
  unregister();
});

etc..

1
ThiagoPXP On

This is probably not the answer you are looking for, however I don't think the digest cycle is the performance killer.

Act upon changes is what may be causing performance issues.

A quick way to avoid the digest cycles acting upon updates is to cache the result of functions instead of binding functions to the HTML templates.

Eg: ng-show="shouldShow()" will be evaluated every time by the digest cycle. If you are able to cache the result of this function in a JS variable in the Controller then use the cached result, you may see performance improvements.

eg: $scope.show = shouldShow(), then ng-show="show"