The Onist

The Onist


Tags


Count the Number of Watchers on an AngularJs Page

Too many watchers in an AngularJs app and you are going to have significant performance problems. Here is a quick tip to print out the number of watchers currently set on a page.

AngularJs performs quite well out of the box for most small to mid-sized applications. However it can very quickly hit performance bottlenecks when large data sets (1000's of items) are set or watched on $scope.

Recently a project here at work hit this bottleneck and not only did the app become extremely sluggish in Chrome and FireFox, but it actually crashed Internet Explorer 9 and 10. We suspected the issue had to do with the large data set that we were attempting to filter on. During the troubleshooting process, we came across this extremely handy piece of code that anyone writing Angular apps may find useful at some point.

(function () { 
    // Change root to point at your ng-app in HTML
    var root = $(document.getElementsByTagName('body'));
    var watchers = [];

    var f = function (element) {
        if (element.data().hasOwnProperty('$scope')) {
            angular.forEach(element.data().$scope.$$watchers, 
                function (watcher) {
                    watchers.push(watcher);
                }
            );
        }

        angular.forEach(element.children(), 
            function (childElement) {
                f($(childElement));
            }
        );
    };

    f(root);

    console.log("Watchers Count: " + watchers.length);
})();

The code above, which was taken from this StackOverflow post, will print out the number of watchers currently set on the page. To use, simply run via the developer console to see how many watchers are currently on the page. From my experience, anything above ~2,000 watchers and you should probably take notice and strongly consider a code refactor.

Hopefully others will find this snippet as useful as we did!

Share Post
View Comments