AnguarJS $watch vs $filter (v5)

Revision 5 of this benchmark created by Justin on


Description

This test compares performance of $watching all elements of the array before and perform a calculation when the targeted values change. The other approach simply use a filter that will always cause the calculations to happen again.

Preparation HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular.min.js">
</script>
<script type="text/javascript">
  // angular bootstraping
  var elementFiltered = angular.element('<div ng-controller="FilteredCtrl">{{values | summit}}</div>');

  var elementWatched = angular.element('<div ng-controller="WatchedCtrl">{{result}}</span></div>');


  angular.module('test', []).filter('summit', function() {
    return function(values) {
      var result = 0;
      for (var i = 0; i < values.length; i++) {
        result += values[i].value;
      }

      return result;
    }
  });

  function FilteredCtrl() {
    // nothing to do
  }

  function WatchedCtrl($scope) {
    $scope.$watch('values', function(values) {
      $scope.result = 0;
      for (var i = 0; i < values.length; i++) {
        $scope.result += values[i].value;
      }
    }, true);
  }

  angular.bootstrap(elementFiltered, ['test']);
  angular.bootstrap(elementWatched, []);

  var scopeFiltered = elementFiltered.scope(),
      scopeWatched = elementWatched.scope();
</script>

Setup

// test related
    var i, current, expected;
    
    function randomize(values) {
      var current, i;
      expected = 0;
      for (i = 0; i < 100; i++) {
        current = values[i] || (values[i] = {});
        current.value = Math.round(Math.random() * 250);
        expected += current.value;
      }
    }
    
    scopeFiltered.values = [];
    scopeWatched.values = [];
    
    randomize(scopeFiltered.values);
    randomize(scopeWatched.values);
    
    scopeFiltered.$apply();
    scopeWatched.$apply();

Teardown


    delete scopeFiltered.values;
    delete scopeWatched.values;
    expected = null;
  

Test runner

Ready to run.

Testing in
TestOps/sec
filter - values changed
randomize(scopeFiltered.values);
scopeFiltered.$apply();
console.log(elementFiltered.text(), expected);
ready
watch - values changed
randomize(scopeWatched.values);
scopeWatched.$apply();
ready
filter - values not changed
scopeFiltered.$apply();
ready
watch - values not changed
scopeWatched.$apply();
ready

Revisions

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

  • Revision 1: published by CaioToOn! on
  • Revision 2: published by CaioToOn! on
  • Revision 3: published by CaioToOn! on
  • Revision 5: published by Justin on