$watchCollection vs $watch

JavaScript performance comparison

Revision 6 of this test case created by Josh Kurz

Info

Cost of Angular's $watchCollection vs $watch

Preparation code

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>

<script>
var app = angular.module('app', []);

var deregs = [];

app.service('Watch', function($rootScope) {
  return {
    run: function() {
      deregs.push($rootScope.$watch('data', function(n, o) {
        if(n[0].obj.obj.boolean === true){
          console.log('yes im the truth');
        } else {
          console.log('boo im false');
        }
      },true));
 
      $rootScope.$digest();
    }
  };
});

app.service('WatchCollection', function($rootScope) {
  return {
    run: function() {
      deregs.push($rootScope.$watchCollection('data', function(n, o) {
        if(n[0].obj.obj.boolean === true){
          console.log('yes im the truth 2');
        } else {
          console.log('boo im false');
        }
      }));
 
      $rootScope.$digest();
    }
  };
});
</script>

<div id="myApp" ng-app="app"></div>
<script>
Benchmark.prototype.setup = function() {
    var i = angular.element(document.getElementById('myApp')).injector();
    var scope = i.get('$rootScope');
    scope.data = [
         {'bob': true, 'obj': {'obj': {'bool': false}}}, {'frank': false}, {'jerry': 'hey'}, {'bargle': false},
         {'bob': true}, {'bob': true}, {'frank': false}, {'jerry': 'hey'},           {'bargle': false},{'bob': true},{'bob': true}, {'frank': false}];
};

Benchmark.prototype.teardown = function() {
    angular.forEach(deregs, function(d) {
      d();
    });
};
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
$watch
var s = i.get('Watch');
s.run();
scope.data[0].obj.obj.boolean = true;
pending…
$watchCollection
var s = i.get('WatchCollection');
s.run();
scope.data[0].obj.obj.boolean = true;
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment