javaCity
javaCity

Reputation: 4318

How many watches are there in a page?

I am doing performance testing in Angular and I want to know exactly how many watches are there in my page. Turns out there is no easy way to do this. Has anyone tried it yet?

Any help will be highly appreciated!

Upvotes: 2

Views: 696

Answers (1)

Nicholas Boll
Nicholas Boll

Reputation: 865

I had the same question. I created a function that will do it:

// get the watch count
// scopeHash is an optional parameter, but if you provide one, this function will modify it for later use (possibly debugging)
function getWatchCount (scope, scopeHash) {
    // default for scopeHash
    if (scopeHash === undefined) {
        scopeHash = {};
    }

    // make sure scope is defined and we haven't already processed this scope
    if (!scope || scopeHash[scope.$id] !== undefined) {
        return 0;
    }

    var watchCount = 0;

    if (scope.$$watchers) {
        watchCount = scope.$$watchers.length;
    }
    scopeHash[scope.$id] = watchCount;

    // get the counts of children and sibling scopes
    // we only need childHead and nextSibling (not childTail or prevSibling)
    watchCount+= getWatchCount(scope.$$childHead, scopeHash);
    watchCount+= getWatchCount(scope.$$nextSibling, scopeHash);

    return watchCount;
}

It will calculate the number of watchers on any scope. It may be most useful to calculate on the root scope, but you can use it at any scope level (possibly to check watches on a component). Here is an example in action: http://jsfiddle.net/S7APg/

Upvotes: 2

Related Questions