AngularJS – Why does $scope.$apply affect other scopes and how it affects performance?

March 29, 2014

one comment

as you can see from Angular’s $apply pseudo-code:

    function $apply(expr) {
      try {
        return $eval(expr);
      } catch (e) {
        $exceptionHandler(e);
      } finally {
        $root.$digest();
      }
    }

Internally angular does the following:

$scope.$apply = $rootScope.$digest //+ some error handling

and since $scope.$apply uses $rootScope, it affects all its descendants by dirty-checking EVERY data-bound objects, it’s crazy, a major hit on performance.

so If you need to update a child scope, you can call $scope.$digest to dirty-check ONLY that scope and its descendants and as a result you reduce the number of dirty-checks and increase your performance.

but be aware, Angular’s documentation favors $apply since it simpler to use $apply all the time and $apply has special error handling that $digest lacks.

Hope you’ll find this post helpful.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

one comment

  1. Florian RibonApril 1, 2014 ב 6:14

    This is insanely usefull, Thank you ! I really need to dig into the source code. There’s a lot of ways to optimize AngularJS for big applications but too bad they seem to currently focus on stability and usability.

    Reply