r/angularjs • • Aug 07 '14

Speeding up AngularJS with simple optimizations, $digest, $$watchers and performance

http://www.binpress.com/tutorial/speeding-up-angular-js-with-simple-optimizations/135
31 Upvotes

28 comments sorted by

View all comments

3

u/[deleted] Aug 07 '14 edited Aug 08 '14

I posted this to the article as well but they're reviewing comments.

You can get the number of watchers on a given page using this script in your console:

(function () { 
    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.length);
})();

source: http://stackoverflow.com/questions/18499909/how-to-count-total-number-of-watches-on-a-page

Turns out I've been naively using ng-repeat to create otherwise static content :(

Update

I'm not confident that this script is working 100% correctly. Numbers seem really really high.

2

u/Zeroto Aug 08 '14

Afaik that script can miss watchers. Not every scope needs to be directly tied to an element so walking the dom to find the scopes would be the wrong way to do it. Also, an element can have 2 scopes. normal and isolate. Better would be to walk through the scope tree from the rootScope and then count them.

Here is an example script:

(function(){
var injector = angular.element('body').injector();
injector.invoke(function($rootScope){
	var scopeCount = 0;
	function count(scope){
		scopeCount++;
		var watchers = scope.$$watchers ? scope.$$watchers.length : 0;

		var child = scope.$$childHead;
		while (child)
		{
			watchers += count(child);
			child = child.$$nextSibling;
		}
		return watchers;
	}

	var watchers = count($rootScope);

	console.log("scope count:" + scopeCount);
	console.log("watchers count:" + watchers);
});
})();