Watching your AngularJS Watchers

Reduce AngularJS Watch Count…


What makes AngularJS more slow than anything else I’ve encountered is having a ton of watchers. For those of you who aren’t familiar with how AngularJS does its two-way databinding, essentially you tell Angular to watch something for changes, and Angular will check it over and over and over and over and over…. and over. Most of the time, the browser is fast enough that this is not a big issue, but many people have found that this can be a real issue as the app (and number of watchers) grows.

Angular adds a watcher to the digest cycle for each of these:

  • {{expression}} — In your templates (and anywhere else where there’s an expression)
  • $scope.$watch(‘expression/function’) — In your JavaScript

Count the Watchers

This simple script will help you identify watch heavy areas of your app:

https://gist.github.com/kentcdodds/31c90402750572107922

Just paste that into your console (or use Chrome snippets) and use like so:

// get all watchers on the whole page
getWatchers();
// get watchers of a specific element (and its children)
getWatchers(document.body);
// select the element of interest in Chrome Dev tools
getWatchers($0);

It will return an array of watchers of the element you gave and all its children.

Surprised? Reduce your watch count…

Lucky for us, Angular 1.3 is shipping with one-time binding which will make it so we can reduce our watch count in the template. This will be super useful. Unfortunately, until you can update your version of Angular, you need to watch out for how many watches you have.

If you’re stuck on < Angular 1.3 then you do have an alternative solution with a module called bindonce that does a good job of reducing your watch count. You may want to take a look at this if you’re in this boat.

Angular’s digest cycle enables one of the best things about working with Angular, but it can come and bite you if you’re not thoughtful about it. Hopefully this helps you identify bottleneck areas of your app.

TestingJavaScript.com Learn the smart, efficient way to test any JavaScript application.