$watchCollection vs $watch (v3)

Revision 3 of this benchmark created by Happy New Year on


Description

Cost of Angular's $watchCollection vs $watch

Preparation HTML

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

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

var deregs = [];

app.run(function($rootScope) {
  $rootScope.data = [
     {'bob': true}, {'frank': false}, {'jerry': 'hey'}, {'bargle': false},
     {'bob': true}, {'bob': true}, {'frank': false}, {'jerry': 'hey'},           {'bargle': false},{'bob': true},{'bob': true}, {'frank': false}];
});

app.service('Watch', function($rootScope) {
  return {
    run: function() {
        
      deregs.push($rootScope.$watch('data', function(n, o) {
      
      },true));
  
      $rootScope.$digest();
    }
  };
});

app.service('WatchCollection', function($rootScope) {
  return {
    run: function() {
      deregs.push($rootScope.$watchCollection('data', function(n, o) {

      }));
  
      $rootScope.$digest();
    }
  };
});

app.service('WatchStrings', function($rootScope) {
  return {
    run: function() {
       
      function getData(){
        var returnString = '';
        for(var i = 0;i < $rootScope.data.length;i++){
          returnString += JSON.stringify($rootScope.data[i]);
        }
        return returnString;
      }

      deregs.push($rootScope.$watch(getData, function(n, o) {
      
      }));
  
      $rootScope.$digest();
    }
  };
});
</script>

<div id="myApp" ng-app="app"></div>

Setup

var i = angular.element(document.getElementById('myApp')).injector();

Teardown


    angular.forEach(deregs, function(d) {
      d();
    });
  

Test runner

Ready to run.

Testing in
TestOps/sec
$watch
var s = i.get('Watch');
s.run();
ready
$watchCollection
var s = i.get('WatchCollection');
s.run();
ready
WatchStrings
var s = i.get('WatchStrings');
s.run();
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.