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

Revision 19 of this benchmark created 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

Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<style>
ul li ul {
  display: block;
}
ul li ul li {
  display: inline-block;
}
</style>
<script>
angular
    .module("testApp",[])
    .run(function($window, $rootScope) {
        $window.$rootScope = $rootScope;
    })
    .controller("testController",function($rootScope, $scope) {
        $scope.items = [];
        for (var i = 0; i < 10; i++) {
            $scope.items.push({
                id: i,
                subItems: (function() {
                    var subItems = [];
                    for (var j = 0; j < 5; j++) {
                        subItems.push({id: j });
                    }
                    return subItems;
                })()
            })
        }
    })
    .directive("listener",function() {
        return {
            restrict: 'C',
            link: function(scope) {
                scope.$on('fooHappened', angular.noop);
            }
        }
    });
</script>

<div ng-app="testApp">
    <div ng-controller="testController">
        <ul>
            <li ng-repeat="item in items">
                <ul>
                    <li ng-repeat="subItem in item.subItems">
                         <span class="listener">{{item.id}}:{{subItem.id}}</span>&nbsp;
                    </li>
                </ul>
            </li>
        </ul>
    </div>
</div>

Test runner

Ready to run.

Testing in
TestOps/sec
$broadcast
window.$rootScope.$broadcast('fooHappened');
ready
$emit
window.$rootScope.$emit('fooHappened');
ready
$broadcast (without matching event)
window.$rootScope.$broadcast('fooNotHappened');
ready
$emit (without matching event)
window.$rootScope.$emit('fooNotHappened');
ready

Revisions

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