$rootScope.emit() vs $rootScope.$broadcast() (v96)

Revision 96 of this benchmark created by prashanth on


Description

This test compares the impact of event bubbling in an angular application and compares it against a "flat" event bus provided by $rootScope.$emit.

The good thing is there should barely cases where you actually need $broadcast. Learn how to avoid it here:

http://stackoverflow.com/a/19498009/288703

the only reason $broadcast in that test outperforms $emit - is because there are 0 listeners to the event in it's $$listeners dict. - basically it does nothing in that test - that's why it's so much faster. Same exact results will be for any angular version for that reason - I've tried 1.4.5 as the highest. But try to add any variation of listener there and $emit and $broadcast will be almost even, but $emit is slightly faster anyways.

So I've updated the new revision with listeners to see the actual picture

Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>

<script>
angular
    .module("testApp",[])
    .controller("testController",function($rootScope, $scope) {

        window.$rootScope = $rootScope;
        var items = $scope.items = [];

        for (i=0;i<100;i++){
            items.push({
                number: i,
                text: 'some text'
            })
        }
  }).directive('superItem', function ($rootScope) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
window.$rootScope = window.$rootScope || $rootScope;

window.$rootScope.$on('fooHappened', function(e) { 
var ok = 1;
    });
        }
    };
});
</script>

<div ng-app="testApp">
    <div ng-controller="testController">
        <ul ng-repeat="item in items">
<li super-item ng-bind="item.number"></li>
        </ul>
    </div>
</div>

Test runner

Ready to run.

Testing in
TestOps/sec
$broadcast with listeneres
window.$rootScope.$broadcast('fooHappened');
ready
$emit with listeneres
window.$rootScope.$emit('fooHappened');
ready
$broadcast with NO listeners
window.$rootScope.$broadcast('noFooHappened');
ready
$emit with NO listeners
window.$rootScope.$emit('noFooHappened');
ready

Revisions

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