SlideShare a Scribd company logo
1 of 25
Download to read offline
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

What's hot

Testing frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabsTesting frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabsTudor Barbu
 
Introduction to A-Frame
Introduction to A-FrameIntroduction to A-Frame
Introduction to A-FrameDaosheng Mu
 
Tek 2013 - Building Web Apps from a New Angle with AngularJS
Tek 2013 - Building Web Apps from a New Angle with AngularJSTek 2013 - Building Web Apps from a New Angle with AngularJS
Tek 2013 - Building Web Apps from a New Angle with AngularJSPablo Godel
 
Роман Лютиков "Web Apps Performance & JavaScript Compilers"
Роман Лютиков "Web Apps Performance & JavaScript Compilers"Роман Лютиков "Web Apps Performance & JavaScript Compilers"
Роман Лютиков "Web Apps Performance & JavaScript Compilers"Fwdays
 
20160905 - BrisJS - nightwatch testing
20160905 - BrisJS - nightwatch testing20160905 - BrisJS - nightwatch testing
20160905 - BrisJS - nightwatch testingVladimir Roudakov
 
AngularJS for Legacy Apps
AngularJS for Legacy AppsAngularJS for Legacy Apps
AngularJS for Legacy AppsPeter Drinnan
 
Testing nightwatch, by David Torroija
Testing nightwatch, by David TorroijaTesting nightwatch, by David Torroija
Testing nightwatch, by David TorroijaDavid Torroija
 
Going Node At Netflix
Going Node At NetflixGoing Node At Netflix
Going Node At NetflixRyan Anklam
 
AngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesAngularJS with TypeScript and Windows Azure Mobile Services
AngularJS with TypeScript and Windows Azure Mobile ServicesRainer Stropek
 
Nightwatch JS for End to End Tests
Nightwatch JS for End to End TestsNightwatch JS for End to End Tests
Nightwatch JS for End to End TestsSriram Angajala
 
Overview of the AngularJS framework
Overview of the AngularJS framework Overview of the AngularJS framework
Overview of the AngularJS framework Yakov Fain
 
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016
Microservices for the Masses with Spring Boot, JHipster, and JWT - Rich Web 2016Matt Raible
 
Performance monitoring measurement angualrjs single page apps with phantomas
Performance monitoring measurement angualrjs single page apps with phantomasPerformance monitoring measurement angualrjs single page apps with phantomas
Performance monitoring measurement angualrjs single page apps with phantomasDavid Amend
 
AngularJS Animations
AngularJS AnimationsAngularJS Animations
AngularJS AnimationsEyal Vardi
 
CSS Regression Tests
CSS Regression TestsCSS Regression Tests
CSS Regression TestsKaloyan Kosev
 

What's hot (20)

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

Similar to JS Memory Leaks & Performance Tips for Angular

jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !Gaurav Behere
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For ManagersAgileThought
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't KnowjQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't Knowgirish82
 
Zend server 6 using zf2, 2013 webinar
Zend server 6 using zf2, 2013 webinarZend server 6 using zf2, 2013 webinar
Zend server 6 using zf2, 2013 webinarYonni Mendes
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
Surviving javascript.pptx
Surviving javascript.pptxSurviving javascript.pptx
Surviving javascript.pptxTamas Rev
 
Javascript essential-pattern
Javascript essential-patternJavascript essential-pattern
Javascript essential-pattern偉格 高
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup PerformanceJustin Cataldo
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript FrameworkAll Things Open
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery ApplicationsRebecca Murphey
 
Awesome html with ujs, jQuery and coffeescript
Awesome html with ujs, jQuery and coffeescriptAwesome html with ujs, jQuery and coffeescript
Awesome html with ujs, jQuery and coffeescriptAmir Barylko
 
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin PovolnyDesign Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin PovolnyManageIQ
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVCAlive Kuo
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 

Similar to JS Memory Leaks & Performance Tips for Angular (20)

jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !
 
Patterns Are Good For Managers
Patterns Are Good For ManagersPatterns Are Good For Managers
Patterns Are Good For Managers
 
AngularJS and SPA
AngularJS and SPAAngularJS and SPA
AngularJS and SPA
 
jQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't KnowjQuery - 10 Time-Savers You (Maybe) Don't Know
jQuery - 10 Time-Savers You (Maybe) Don't Know
 
Zend server 6 using zf2, 2013 webinar
Zend server 6 using zf2, 2013 webinarZend server 6 using zf2, 2013 webinar
Zend server 6 using zf2, 2013 webinar
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Surviving javascript.pptx
Surviving javascript.pptxSurviving javascript.pptx
Surviving javascript.pptx
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
Javascript essential-pattern
Javascript essential-patternJavascript essential-pattern
Javascript essential-pattern
 
Frontin like-a-backer
Frontin like-a-backerFrontin like-a-backer
Frontin like-a-backer
 
#NewMeetup Performance
#NewMeetup Performance#NewMeetup Performance
#NewMeetup Performance
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript Framework
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 
J query
J queryJ query
J query
 
Awesome html with ujs, jQuery and coffeescript
Awesome html with ujs, jQuery and coffeescriptAwesome html with ujs, jQuery and coffeescript
Awesome html with ujs, jQuery and coffeescript
 
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin PovolnyDesign Summit - UI Roadmap - Dan Clarizio, Martin Povolny
Design Summit - UI Roadmap - Dan Clarizio, Martin Povolny
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 

Recently uploaded

Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 

Recently uploaded (20)

Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 

JS Memory Leaks & Performance Tips for 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