Search code examples
angularjsangularjs-scopeangularjs-rootscope

Angular: using $rootScope.$on vs $scope.$on to catch a $rootScope.$broadcast in a component – what is better in terms of performance?


Hi I’m wondering what is better in terms of performance. Let’s say I have this factory that broadcasts stuff:

angular.module('core.foo')
  .factory('Foo',
    ['$rootScope', 
      function FooFactory($rootScope) {

        $rootScope.$broadcast('bar', baz);

      }
    ]
  );

And have a component somewhere (or a lot of them) listening for that event. What would be better?

To use $rootScope.$on:

angular.module('foo').component('foo', {
  templateUrl: 'foo.html',
  controller: ['$rootScope',
    function FooController($rootScope) {

      $rootScope.$on('bar', function(event, data){
        // use the data
      });

    }]
});

or $scope.$on:

angular.module('foo').component('foo', {
  templateUrl: 'foo.html',
  controller: ['$scope',
    function FooController($scope) {

      $scope.$on('bar', function(event, data){
        // use the data
      });

    }]
});

Both would work, I’m just curious.


Solution

  • I don't really understand why people here seem to be so obsessed with performance. You should only worry about performance when you have a performance problem. Otherwise, it's premature optimization, which is the root of all evil.

    In that case, the evil might be memory leaks, and much performance problems.

    A controller has a scope that has the same life-cycle as the controller. $rootScope on the other hand is a singleton.

    So, if you add a listener to the root scope, and forget to remove it when it's not needed anymore, you'll have a memory leak. The listener, which has an implicit reference to the controller, which has an implicit reference to its scope, will stay alive, consume memory, and continue reacting to events for no reason.

    If you add a listener to the scope of the controller, however, when the scope and the controller are destroyed, then nobody will have a reference to the listener anymore, and everything will be garbage collected.

    So, strive for simplicity, maintainability, testability and correctness first. Performance should not be your primary concern. The framework makes sure every natural, documented way of using the framework is fast enough.