AngularJS: $Broadcast & $emit

Benchmark created by Benjamin Longearet on


Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
<script>
var testModule = angular.module('test', [])
.controller('myFirstController', function ($scope, $rootScope) {
  $scope.data = _.range(100);
})
.controller('mySecondController', function ($scope, $rootScope) {})
.controller('myThirdController', function ($scope, $rootScope) {})
.controller('myFourthController', function ($scope, $rootScope) {

  // bind $scope.$on
  $scope.$on('my_event_scope', function (a,b,c,d) {
    var none = undefined;
  });

  // bind $scope.$on
  $rootScope.$on('my_event_rootscope', function (a,b,c,d) {
    var none = undefined;
  });

  window.testEmitScopeOnScope = function () {
    $scope.$emit('my_event_scope');
    try { $scope.$apply(); } catch (e) {}
  };
  window.testBroadcastRootscopeOnScope = function () {
    $rootScope.$broadcast('my_event_scope');
    try { $scope.$apply(); } catch (e) {}
  };
  window.testEmitRootscopeOnRootcope = function () {
    $rootScope.$emit('my_event_rootscope');
    try { $scope.$apply(); } catch (e) {}
  };

});;
</script>
<div ng-app="test">
  <div ng-controller="myFirstController">
    <div ng-repeat="d in data" ng-controller="mySecondController">
      <div ng-controller="myThirdController">
        <div ng-controller="myFourthController"></div>
      </div>
    </div>
  </div>
</div>

Test runner

Ready to run.

Testing in
TestOps/sec
$broadcast on rootScope and $on on controller
window.testBroadcastRootscopeOnScope();
ready
$emit/$on on same controller
window.testEmitScopeOnScope();
ready
$emit/$on on rootScope
window.testEmitRootscopeOnRootcope();
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Benjamin Longearet on