SlideShare a Scribd company logo
JS Performance &
Memory Leaks
Keep Yo Angular Running Snappy
How To Think of Memory
• It a graph!
How To Think of Memory
• Something a little more visual
Common Memory Leak
Cases
someDiv = document.createElement(“div”);
display.appendChild(someDiv);
//Some other code
display.removeAllChildern();
// Oh no zombie div, it’s still alive!
Them Dom Leaks
Common Memory Leak
Cases
var a = function () {
var largeStr = new Array(1000000).join('x');
return function () {
return largeStr;
};
}();
// largeStr can stick around
Closures are awesome till they arent
Common Memory Leak
Cases
var myObj = {
     callMeMaybe: function () {
          var myRef = this;
          var val = setTimeout(function () {
               myRef.callMeMaybe();
          }, 1000);
     }
};
myObj.callMeMaybe();
myObj = null; // This aint gonna cut it
Those Damn Timeouts
Solving Memory Leaks in
AngularJS
$scope.on('$destroy', function(){
// KILL
// ALL
// REFERENCES
// NOW
});
Use $destroy to clean up!
Solving Memory Leaks in
AngularJS
Use $destroy to clean up!
• Unbind event-listeners: element.off(‘click’)
• Kill your watchers:
• var unwatch = scope.$watch(…
• unwatch(); // Watcher is dead
Solving Memory Leaks in
AngularJS
Use $destroy to clean up!
var button = scope.button = {
selected: false,
callback: scope.onSelect || angular.noop
};
};
scope.$destroy(…
button = null;
…);
How to Find Memory Issues
• CHROME DEV TOOLS!!!!
• https://developer.chrome.com/devtools/docs/
javascript-memory-profiling
Fruits of our Efforts
Performance
How do we keep Angular snappy?
Understanding the Angular
Digest Cycle
Triggers: $apply, $digest, $timeout, ngClick
Psst… Dont use mouse move events (or them debounce)
Performance Tips
$digest triggers digest cycle in current scope and below
V.S.
$apply starts at $rootScope and goes down
Try $applyAsync([exp]);
This can be used to queue up multiple expressions which
need to be evaluated in the same digest.
Using $digest() V.S. $apply() -> $$watchers
Think of scopes and watcher like a tree from the $rootScope
Performance Tips
• Avoiding creating a Watcher programmatically
• watchers > 2000 = caution zone // code smell
• Try services or event dispatching
• Were using ngStats to count that
• DEMO!
var unbinder = scope.$watch('scopeValueToBeWatcher',
function(newVal, oldVal){})
Watch your Watchers
Performance Tips
• Binds once and then deregisters watcher
• Dont use it when you expect the value to change
{{::omgOneAndDoneBinding}}
Use One-Way Bindings!!
Performance Tips
• Dont use them
• If you have to: $rootScope.$emit(…);
• What we did: event-dispatch.js
• Doesnt rely on digest cycle
• Dispatcher/Callback register
• Dispatcher.listen('MediaFilter:Filtered', func…);
$broadcast calls all registered listeners from scope DOWN
V.S.
$emit calls all registered listeners from scope UP
$broadcast V.S. $emit
Performance Tips
• Dont use them on the DOM
• They are run twice per digest cycle, once when
anything changes, and another time to collect
further changes, and do not actually remove any
part of the collection from memory
• BLAH -> {{ array | filter }}
• Do it in the controller -> $filter('filter')(array)
$filter
Performance Tips
• ng-hide and ng-show simply toggle the CSS
display property.
• What that means everything is just hiding but
the $$watchers are still registered
• ng-if remove elements off the DOM
• That means anything inside is gone along with
the $$watchers
ngShow/ngHide V.S ngIf/ngSwitch
Performance Tips
Crazy DOM Logic
%ng-include(src="show.template")
Show Logic:
if ( item.sucks() ) {
show.template = ‘sucks.html';
} else if ( item.awesome() ) {
show.template = ‘awesome.html';
}
• Have crazy logic using ng-if?
• Try ng-include!
Performance Tips
Crazy DOM Logic For Directives
templateUrl: function(tElement, tAttrs) {



if (tAttrs === ‘photo’) {

return ‘somePhotoTemplate’;

} else {

return ‘otherTemplate’;
}
…



}
Use attributes passed to directives to choose template
Performance Tips
$http Performance Boost
• app.config(function ($httpProvider) { 

$httpProvider.useApplyAsync(true); 

});
• Configure $http service to combine processing
of multiple http responses received at around
the same time via $rootScope.$applyAsync. This
can result in significant performance
improvement for bigger applications that make
many HTTP requests concurrently (common
during application bootstrap).
Performance Tips
ng-repeat Can Get Nasty
• Mo’ DOM elements mo’ problems (watchers)
• ng-repeat="model in collection track by model.id”
• ngRepeat will not have to rebuild the DOM elements
for already rendered items, even if the JavaScript
objects in the collection have been substituted
• angular-viewport-watch to the rescue
• http://.github.com/shahata/angular-viewport-watch
• Hide them $$watchers
• DEMO!
Keeping Digest Cycle Fast
• Keeping watcher count down
• Avoid making new $watchers
• Use on way bindings
• {{::oneWay}}
• Logic triggered by digest cycle should be fast
• ng-repeat="a in getItems()"
• Avoid creating new scopes, mo’ scope mo’ slow
• ngIf over ngShow
• Avoid $emit and $broadcast
• Watchers and Digest cycles arent evil just have
to use them wisely
fin

More Related Content

PDF
AngularJS - Overcoming performance issues. Limits.
PDF
AngularJS performance & production tips
PPTX
Angularjs Performance
PDF
AngularJS best-practices
PDF
Integrating Angular js & three.js
PDF
Night Watch with QA
PPTX
Jasmine with JS-Test-Driver
PDF
Introduction to WebGL and WebVR
AngularJS - Overcoming performance issues. Limits.
AngularJS performance & production tips
Angularjs Performance
AngularJS best-practices
Integrating Angular js & three.js
Night Watch with QA
Jasmine with JS-Test-Driver
Introduction to WebGL and WebVR

What's hot (20)

ODP
AngularJs Crash Course
PPTX
Testing frontends with nightwatch & saucelabs
PDF
Introduction to A-Frame
PDF
Tek 2013 - Building Web Apps from a New Angle with AngularJS
PDF
Роман Лютиков "Web Apps Performance & JavaScript Compilers"
PDF
20160905 - BrisJS - nightwatch testing
PPT
AngularJS for Legacy Apps
PDF
AngularJS Framework
PDF
Testing nightwatch, by David Torroija
PDF
Going Node At Netflix
PPTX
AngularJS with TypeScript and Windows Azure Mobile Services
PPTX
Nightwatch JS for End to End Tests
PDF
Webrender 1.0
PDF
Overview of the AngularJS framework
PDF
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
PDF
Performance monitoring measurement angualrjs single page apps with phantomas
PPTX
Angular js architecture (v1.4.8)
PPTX
AngularJS Animations
PPTX
Angularjs Basics
PPTX
CSS Regression Tests
AngularJs Crash Course
Testing frontends with nightwatch & saucelabs
Introduction to A-Frame
Tek 2013 - Building Web Apps from a New Angle with AngularJS
Роман Лютиков "Web Apps Performance & JavaScript Compilers"
20160905 - BrisJS - nightwatch testing
AngularJS for Legacy Apps
AngularJS Framework
Testing nightwatch, by David Torroija
Going Node At Netflix
AngularJS with TypeScript and Windows Azure Mobile Services
Nightwatch JS for End to End Tests
Webrender 1.0
Overview of the AngularJS framework
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
Performance monitoring measurement angualrjs single page apps with phantomas
Angular js architecture (v1.4.8)
AngularJS Animations
Angularjs Basics
CSS Regression Tests
Ad

Similar to Javascript Memory leaks and Performance & Angular (20)

PPTX
Dive into Angular, part 3: Performance
PPT
Angular js meetup
PPT
angularjsmeetup-150303044616-conversion-gate01
PDF
Dragos Rusu - Angular JS - Overcoming Performance Issues - CodeCamp-10-may-2014
PPTX
AngularJS Best Practices
PPTX
Optimizing a large angular application (ng conf)
PPTX
Optimizing Angular Performance in Enterprise Single Page Apps
PDF
AngularJS Workshop
PDF
Advanced Tips & Tricks for using Angular JS
PPT
Angular Seminar-js
PPTX
AngularJS roadmap.
PDF
AngularJS in practice
PPTX
JavaScripters Event Oct 22, 2016 · 2:00 PM: Common Mistakes made by Angular D...
PPTX
AngularJs presentation
PPTX
Angular workshop - Full Development Guide
PPTX
Scope demystified - AngularJS
PPTX
Understanding angular js
PPTX
AngularJS Introduction (Talk given on Aug 5 2013)
PPTX
Bhuvi ppt zerobug
ODP
Angular js-crash-course
Dive into Angular, part 3: Performance
Angular js meetup
angularjsmeetup-150303044616-conversion-gate01
Dragos Rusu - Angular JS - Overcoming Performance Issues - CodeCamp-10-may-2014
AngularJS Best Practices
Optimizing a large angular application (ng conf)
Optimizing Angular Performance in Enterprise Single Page Apps
AngularJS Workshop
Advanced Tips & Tricks for using Angular JS
Angular Seminar-js
AngularJS roadmap.
AngularJS in practice
JavaScripters Event Oct 22, 2016 · 2:00 PM: Common Mistakes made by Angular D...
AngularJs presentation
Angular workshop - Full Development Guide
Scope demystified - AngularJS
Understanding angular js
AngularJS Introduction (Talk given on Aug 5 2013)
Bhuvi ppt zerobug
Angular js-crash-course
Ad

Recently uploaded (20)

PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
System and Network Administration Chapter 2
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
L1 - Introduction to python Backend.pptx
PDF
System and Network Administraation Chapter 3
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PPTX
Introduction to Artificial Intelligence
PDF
top salesforce developer skills in 2025.pdf
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
Transform Your Business with a Software ERP System
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
How Creative Agencies Leverage Project Management Software.pdf
How to Choose the Right IT Partner for Your Business in Malaysia
System and Network Administration Chapter 2
PTS Company Brochure 2025 (1).pdf.......
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
L1 - Introduction to python Backend.pptx
System and Network Administraation Chapter 3
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Introduction to Artificial Intelligence
top salesforce developer skills in 2025.pdf
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Wondershare Filmora 15 Crack With Activation Key [2025
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
How to Migrate SBCGlobal Email to Yahoo Easily
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Navsoft: AI-Powered Business Solutions & Custom Software Development
2025 Textile ERP Trends: SAP, Odoo & Oracle
Transform Your Business with a Software ERP System
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
How Creative Agencies Leverage Project Management Software.pdf

Javascript Memory leaks and Performance & Angular

  • 1. JS Performance & Memory Leaks Keep Yo Angular Running Snappy
  • 2. How To Think of Memory • It a graph!
  • 3. How To Think of Memory • Something a little more visual
  • 4. Common Memory Leak Cases someDiv = document.createElement(“div”); display.appendChild(someDiv); //Some other code display.removeAllChildern(); // Oh no zombie div, it’s still alive! Them Dom Leaks
  • 5. Common Memory Leak Cases var a = function () { var largeStr = new Array(1000000).join('x'); return function () { return largeStr; }; }(); // largeStr can stick around Closures are awesome till they arent
  • 6. Common Memory Leak Cases var myObj = {      callMeMaybe: function () {           var myRef = this;           var val = setTimeout(function () {                myRef.callMeMaybe();           }, 1000);      } }; myObj.callMeMaybe(); myObj = null; // This aint gonna cut it Those Damn Timeouts
  • 7. Solving Memory Leaks in AngularJS $scope.on('$destroy', function(){ // KILL // ALL // REFERENCES // NOW }); Use $destroy to clean up!
  • 8. Solving Memory Leaks in AngularJS Use $destroy to clean up! • Unbind event-listeners: element.off(‘click’) • Kill your watchers: • var unwatch = scope.$watch(… • unwatch(); // Watcher is dead
  • 9. Solving Memory Leaks in AngularJS Use $destroy to clean up! var button = scope.button = { selected: false, callback: scope.onSelect || angular.noop }; }; scope.$destroy(… button = null; …);
  • 10. How to Find Memory Issues • CHROME DEV TOOLS!!!! • https://developer.chrome.com/devtools/docs/ javascript-memory-profiling
  • 11. Fruits of our Efforts
  • 12. Performance How do we keep Angular snappy?
  • 13. Understanding the Angular Digest Cycle Triggers: $apply, $digest, $timeout, ngClick Psst… Dont use mouse move events (or them debounce)
  • 14. Performance Tips $digest triggers digest cycle in current scope and below V.S. $apply starts at $rootScope and goes down Try $applyAsync([exp]); This can be used to queue up multiple expressions which need to be evaluated in the same digest. Using $digest() V.S. $apply() -> $$watchers Think of scopes and watcher like a tree from the $rootScope
  • 15. Performance Tips • Avoiding creating a Watcher programmatically • watchers > 2000 = caution zone // code smell • Try services or event dispatching • Were using ngStats to count that • DEMO! var unbinder = scope.$watch('scopeValueToBeWatcher', function(newVal, oldVal){}) Watch your Watchers
  • 16. Performance Tips • Binds once and then deregisters watcher • Dont use it when you expect the value to change {{::omgOneAndDoneBinding}} Use One-Way Bindings!!
  • 17. Performance Tips • Dont use them • If you have to: $rootScope.$emit(…); • What we did: event-dispatch.js • Doesnt rely on digest cycle • Dispatcher/Callback register • Dispatcher.listen('MediaFilter:Filtered', func…); $broadcast calls all registered listeners from scope DOWN V.S. $emit calls all registered listeners from scope UP $broadcast V.S. $emit
  • 18. Performance Tips • Dont use them on the DOM • They are run twice per digest cycle, once when anything changes, and another time to collect further changes, and do not actually remove any part of the collection from memory • BLAH -> {{ array | filter }} • Do it in the controller -> $filter('filter')(array) $filter
  • 19. Performance Tips • ng-hide and ng-show simply toggle the CSS display property. • What that means everything is just hiding but the $$watchers are still registered • ng-if remove elements off the DOM • That means anything inside is gone along with the $$watchers ngShow/ngHide V.S ngIf/ngSwitch
  • 20. Performance Tips Crazy DOM Logic %ng-include(src="show.template") Show Logic: if ( item.sucks() ) { show.template = ‘sucks.html'; } else if ( item.awesome() ) { show.template = ‘awesome.html'; } • Have crazy logic using ng-if? • Try ng-include!
  • 21. Performance Tips Crazy DOM Logic For Directives templateUrl: function(tElement, tAttrs) {
 
 if (tAttrs === ‘photo’) {
 return ‘somePhotoTemplate’;
 } else {
 return ‘otherTemplate’; } …
 
 } Use attributes passed to directives to choose template
  • 22. Performance Tips $http Performance Boost • app.config(function ($httpProvider) { 
 $httpProvider.useApplyAsync(true); 
 }); • Configure $http service to combine processing of multiple http responses received at around the same time via $rootScope.$applyAsync. This can result in significant performance improvement for bigger applications that make many HTTP requests concurrently (common during application bootstrap).
  • 23. Performance Tips ng-repeat Can Get Nasty • Mo’ DOM elements mo’ problems (watchers) • ng-repeat="model in collection track by model.id” • ngRepeat will not have to rebuild the DOM elements for already rendered items, even if the JavaScript objects in the collection have been substituted • angular-viewport-watch to the rescue • http://.github.com/shahata/angular-viewport-watch • Hide them $$watchers • DEMO!
  • 24. Keeping Digest Cycle Fast • Keeping watcher count down • Avoid making new $watchers • Use on way bindings • {{::oneWay}} • Logic triggered by digest cycle should be fast • ng-repeat="a in getItems()" • Avoid creating new scopes, mo’ scope mo’ slow • ngIf over ngShow • Avoid $emit and $broadcast • Watchers and Digest cycles arent evil just have to use them wisely
  • 25. fin