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.
Dragos Mihai Rusu
 
PDF
AngularJS performance & production tips
Nir Kaufman
 
PPTX
Angularjs Performance
Steven Lambert
 
PDF
AngularJS best-practices
Henry Tao
 
PDF
Integrating Angular js & three.js
Josh Staples
 
PDF
Night Watch with QA
Carsten Sandtner
 
PPTX
Jasmine with JS-Test-Driver
Devesh Chanchlani
 
PDF
Introduction to WebGL and WebVR
Daosheng Mu
 
AngularJS - Overcoming performance issues. Limits.
Dragos Mihai Rusu
 
AngularJS performance & production tips
Nir Kaufman
 
Angularjs Performance
Steven Lambert
 
AngularJS best-practices
Henry Tao
 
Integrating Angular js & three.js
Josh Staples
 
Night Watch with QA
Carsten Sandtner
 
Jasmine with JS-Test-Driver
Devesh Chanchlani
 
Introduction to WebGL and WebVR
Daosheng Mu
 

What's hot (20)

ODP
AngularJs Crash Course
Keith Bloomfield
 
PPTX
Testing frontends with nightwatch & saucelabs
Tudor Barbu
 
PDF
Introduction to A-Frame
Daosheng Mu
 
PDF
Tek 2013 - Building Web Apps from a New Angle with AngularJS
Pablo Godel
 
PDF
Роман Лютиков "Web Apps Performance & JavaScript Compilers"
Fwdays
 
PDF
20160905 - BrisJS - nightwatch testing
Vladimir Roudakov
 
PPT
AngularJS for Legacy Apps
Peter Drinnan
 
PDF
AngularJS Framework
Barcamp Saigon
 
PDF
Testing nightwatch, by David Torroija
David Torroija
 
PDF
Going Node At Netflix
Ryan Anklam
 
PPTX
AngularJS with TypeScript and Windows Azure Mobile Services
Rainer Stropek
 
PPTX
Nightwatch JS for End to End Tests
Sriram Angajala
 
PDF
Webrender 1.0
Daosheng Mu
 
PDF
Overview of the AngularJS framework
Yakov Fain
 
PDF
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
Matt Raible
 
PDF
Performance monitoring measurement angualrjs single page apps with phantomas
David Amend
 
PPTX
Angular js architecture (v1.4.8)
Gabi Costel Lapusneanu
 
PPTX
AngularJS Animations
Eyal Vardi
 
PPTX
Angularjs Basics
Anuradha Bandara
 
PPTX
CSS Regression Tests
Kaloyan Kosev
 
AngularJs Crash Course
Keith Bloomfield
 
Testing frontends with nightwatch & saucelabs
Tudor Barbu
 
Introduction to A-Frame
Daosheng Mu
 
Tek 2013 - Building Web Apps from a New Angle with AngularJS
Pablo Godel
 
Роман Лютиков "Web Apps Performance & JavaScript Compilers"
Fwdays
 
20160905 - BrisJS - nightwatch testing
Vladimir Roudakov
 
AngularJS for Legacy Apps
Peter Drinnan
 
AngularJS Framework
Barcamp Saigon
 
Testing nightwatch, by David Torroija
David Torroija
 
Going Node At Netflix
Ryan Anklam
 
AngularJS with TypeScript and Windows Azure Mobile Services
Rainer Stropek
 
Nightwatch JS for End to End Tests
Sriram Angajala
 
Webrender 1.0
Daosheng Mu
 
Overview of the AngularJS framework
Yakov Fain
 
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
Matt Raible
 
Performance monitoring measurement angualrjs single page apps with phantomas
David Amend
 
Angular js architecture (v1.4.8)
Gabi Costel Lapusneanu
 
AngularJS Animations
Eyal Vardi
 
Angularjs Basics
Anuradha Bandara
 
CSS Regression Tests
Kaloyan Kosev
 
Ad

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

PPTX
Dive into Angular, part 3: Performance
Oleksii Prohonnyi
 
PPT
Angular js meetup
Pierre-Yves Gicquel
 
PPT
angularjsmeetup-150303044616-conversion-gate01
Teo E
 
PDF
Dragos Rusu - Angular JS - Overcoming Performance Issues - CodeCamp-10-may-2014
Codecamp Romania
 
PPTX
AngularJS Best Practices
Narek Mamikonyan
 
PPTX
Optimizing a large angular application (ng conf)
A K M Zahiduzzaman
 
PPTX
Optimizing Angular Performance in Enterprise Single Page Apps
Morgan Stone
 
PDF
AngularJS Workshop
Gianluca Cacace
 
PDF
Advanced Tips & Tricks for using Angular JS
Simon Guest
 
PPT
Angular Seminar-js
Mindfire Solutions
 
PPTX
AngularJS roadmap.
Dmitriy Korol
 
PDF
AngularJS in practice
Eugene Fidelin
 
PPTX
JavaScripters Event Oct 22, 2016 · 2:00 PM: Common Mistakes made by Angular D...
JavaScripters Community
 
PPTX
AngularJs presentation
Phan Tuan
 
PPTX
Angular workshop - Full Development Guide
Nitin Giri
 
PPTX
Scope demystified - AngularJS
Sumanth krishna
 
PPTX
Understanding angular js
Aayush Shrestha
 
PPTX
AngularJS Introduction (Talk given on Aug 5 2013)
Abhishek Anand
 
PPTX
Bhuvi ppt zerobug
BhuviS3
 
ODP
Angular js-crash-course
Keith Bloomfield
 
Dive into Angular, part 3: Performance
Oleksii Prohonnyi
 
Angular js meetup
Pierre-Yves Gicquel
 
angularjsmeetup-150303044616-conversion-gate01
Teo E
 
Dragos Rusu - Angular JS - Overcoming Performance Issues - CodeCamp-10-may-2014
Codecamp Romania
 
AngularJS Best Practices
Narek Mamikonyan
 
Optimizing a large angular application (ng conf)
A K M Zahiduzzaman
 
Optimizing Angular Performance in Enterprise Single Page Apps
Morgan Stone
 
AngularJS Workshop
Gianluca Cacace
 
Advanced Tips & Tricks for using Angular JS
Simon Guest
 
Angular Seminar-js
Mindfire Solutions
 
AngularJS roadmap.
Dmitriy Korol
 
AngularJS in practice
Eugene Fidelin
 
JavaScripters Event Oct 22, 2016 · 2:00 PM: Common Mistakes made by Angular D...
JavaScripters Community
 
AngularJs presentation
Phan Tuan
 
Angular workshop - Full Development Guide
Nitin Giri
 
Scope demystified - AngularJS
Sumanth krishna
 
Understanding angular js
Aayush Shrestha
 
AngularJS Introduction (Talk given on Aug 5 2013)
Abhishek Anand
 
Bhuvi ppt zerobug
BhuviS3
 
Angular js-crash-course
Keith Bloomfield
 
Ad

Recently uploaded (20)

PDF
Exploring AI Agents in Process Industries
amoreira6
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PDF
Become an Agentblazer Champion Challenge
Dele Amefo
 
PDF
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
PDF
Bandai Playdia The Book - David Glotz
BluePanther6
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PDF
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
PDF
Microsoft Teams Essentials; The pricing and the versions_PDF.pdf
Q-Advise
 
PPTX
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
PDF
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
PDF
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
PPTX
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PDF
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Hironori Washizaki
 
PDF
Protecting the Digital World Cyber Securit
dnthakkar16
 
DOCX
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
PDF
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
PPTX
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
PDF
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
ESUG
 
Exploring AI Agents in Process Industries
amoreira6
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
Become an Agentblazer Champion Challenge
Dele Amefo
 
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
Bandai Playdia The Book - David Glotz
BluePanther6
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
Microsoft Teams Essentials; The pricing and the versions_PDF.pdf
Q-Advise
 
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Hironori Washizaki
 
Protecting the Digital World Cyber Securit
dnthakkar16
 
The Future of Smart Factories Why Embedded Analytics Leads the Way
Varsha Nayak
 
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
ESUG
 

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