Skip to content

Instantly share code, notes, and snippets.

@aj07mm
Forked from felippenardi/readme.md
Last active August 29, 2015 14:23
Show Gist options
  • Save aj07mm/388cd260b2356a7ca148 to your computer and use it in GitHub Desktop.
Save aj07mm/388cd260b2356a7ca148 to your computer and use it in GitHub Desktop.

Benchmarking AngularJS performance

Things to optmize

  • Use one-time-bind on expressions ( {{::value}} )
  • Replace $scope.$apply() with $scope.$digest() whenever possible
  • Move filters to controllers

Measuring Watch list

To get the total watchers on the current page, you can run this script on the browser console:

function getWatchers(root) {
  root = angular.element(root || document.documentElement);

  var watcherCount = 0;
 
  function getElemWatchers(element) {
    var isolateWatchers = getWatchersFromScope(element.data().$isolateScope);
    var scopeWatchers = getWatchersFromScope(element.data().$scope);
    var watchers = scopeWatchers.concat(isolateWatchers);
    angular.forEach(element.children(), function (childElement) {
      watchers = watchers.concat(getElemWatchers(angular.element(childElement)));
    });
    return watchers;
  }
  
  function getWatchersFromScope(scope) {
    if (scope) {
      return scope.$$watchers || [];
    } else {
      return [];
    }
  }
 
  return getElemWatchers(root);
}
getWatchers().length

Measuring Time

To get information of time that an operation takes, you use one of these two methods:

Manually

Run:

window.performance.mark('begin_operation');

Just before the operation starts. Then:

window.performance.mark('finish_operation');

When it ends. Then:

window.performance.measure('operation', 'begin_operation', 'finish_operation')

The result will be stored on:

window.performance.getEntriesByType('measure')[0].duration

The output is in miliseconds with microseconds units.

Automatically

1- Go to you chrome Profiles tab on developer tools 2- Click on record 3- Do an specific operation 4- Pause recording

The idle time can be ignored, what we are looking for here is the program time.

You can see how much time every operation took and even some suggestion right away on what to improve (the exclamation marks).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment