SlideShare a Scribd company logo
1 of 74
Download to read offline
AngularJS.
Performance &
Limits.
Dragos Rusu - CodeCamp Iasi 2014
(dragos.rusu@bytex.ro)
Our story
From
"We have to rethink this whole module, remove time navigation... it's just too sluggish." ★
to
"It's awesome, really fast, it's like going from night to day!" ★
(★) SOFTVISION customer
A few words about me
Dragos Rusu @ SOFTVISION
WEB/ZEND ENGINEER since 2007 (backend, frontend)
ARTICLE WRITER (PHP Architect)
PROJECTS: platforms for airlines (Cathay Pacific, Singapore Airlines, Air Berlin), tourism agencies,
home automation and security, agriculture
We will discuss about...
1. View watches / data bindings
2. What you see is what you show
3. The risk of polluting scopes
4. Core directives to avoid
5. Splitting the page
6. Miscellaneous
7. Limits
Q / A
disclaimer
PERFORMANCE principles for heavy apps (+500 man days)
* many items are not covered here.
* code samples - only in AngularJS
never used AngularJS before? no problem, principles are general, yet the solutions are particular.
Shall we?
1. View watches / data bindings
GENERAL CONTEXT
"more of 2000 watchers can lag the UI" (angular-tips.com)
"the expressions in curly braces denote bindings" ({{ ... }}) (docs.angularjs.org)
"AngularJS internally creates a $watch for each ng-* directive" (github.com/Pasvaz/bindonce)
"ngRepeat directive instantiates a template once per item [...] each template instance gets its own
scope" (docs.angularjs.org)
Ok... but why would I be counting watches?
Every watcher is run at the digest cycle. The digest cycle is repeated until none of the results has
changed value
(Brian Ford - AngularJS contributor)
✈ A peak into AngularJS source code
$apply:function(expr){
try{
beginPhase('$apply');
returnthis.$eval(expr);
}catch(e){$exceptionHandler(e);
}finally{
clearPhase();
try{
$rootScope.$digest();//Ouhmy...
//[...]
?
https://github.com/angular/angular.js/blob/
master/src/ng/rootScope.js#L943
(1) double-binding creates tons of listeners
SOLUTION:
Whenever feasible, use single-binding solutions
double binding DEMO / bindonce DEMO
Why? Is double-binding slow?
Not quite. The AngularJS way of implementing it is slow ($dirty flags instead of observable
properties).
pssst: ECMA6: Object.observe()
github.com/Pasvaz/bindonce
github.com/kseamon/fast-bind
pssst: bindonce will be part of AngularJS 1.3 release!
(2) direct function calls from templates are called very often
SOLUTION: pre-compute the values to shown in the view model (default values, totals, etc)
<ul>
<ling-repeat="iteminitems">
//{{item.name}}({{computeTotal(item)}})
{{item.name}}({{item.computedTotal}})
</li>
</ul>
?
EXAMPLE
vatTotal will be recomputed on each scope $digest, regardless if the values that vatTotal() depend on
are changed or not (DEMO)
//...controller...
$scope.vat=24;//%
$scope.vatTotal=function(){
return(
$scope.data.item.total*
(1+$scope.vat/100)
);
};
//...template...
{{vatTotal()}}
?
(3) iterating over large data sets slows down the page
SOLUTION: create a lightweight iterable view model
angular.module('codecamp').controller('testCtrl',[
'$scope','dm','$q',function($scope,dm,$q){
'usestrict';
$scope._init=function(){
$scope.testViewModel={};
$q.all([dm.getData1(),dm.getData2()])
.then(function(response){
$scope.computeViewModel(response.data);
}
);
};
$scope._init();
}
);
?
(4) ng-repeat extra DOM manipulations
SOLUTION: ng-repeat with track by id (DEMO)
<ul>
<ling-repeat="iteminitemstrackbyitem.id">
{{item.name}}
</li>
</ul>
?
(5) filters are called very often
SOLUTION: lightweight quasi-independent filters
<span>{{value}}</span>
<ul>
<ling-repeat="iteminitems">
{{item.name|heavyFilteritem.value,$index}}
</li>
</ul>
?
WARNING: avoid touching DOM in filters and watches
(6) multiple recursive $watch might cause page flickering
SOLUTION: try to avoid recursive watch, where feasible
$scope.$watch('model.items',
function(newValue,oldValue){
//dosmth
},recursive=true);
);
?
(7) direct DOM watch functions might slow down the page
SOLUTION: try to avoid complex valueExpression, where feasible (use the data model instead)
//DirectiveLINKfunction
link:function($scope,$el,$attrs){
$scope.$watch(
function(){return$el[0].childNodes.length;},
function(newValue,oldValue){}
);
}
?
SOURCE: stackoverflow.com/questions/21332671
1. View watches / data bindings
2. What you see is what you show
3. The risk of polluting scopes
4. Core directives to avoid
5. Splitting the page
6. Miscellaneous
7. Limits
2. What you see is what you show
ng-if vs. ng-show (1)
ng-hide and ng-show makes no speed difference (DEMO)
<ulng-hide="hideCondition">
<ling-repeat="iteminitems">
{{item.value}}
</li>
</ul>
?
ng-if vs. ng-show (2)
ng-if/ng-switch might make a difference on more content
(e.g. tabbed page)
<ulng-if="displayCondition">
//CONTENT
</ul>
?
* fewer bindings
* fewer linkers called at startup
remove non-visible elements in the scroll (1)
one easy way would be PAGINATION
doesn't always apply though...
remove non-visible elements in the scroll (2)
DISPLAY elements, but ONLY THE VISIBLE ones
known as the VIRTUAL/INFINITE SCROLLING problem
remove non-visible elements in the scroll (3)
usually occurs when large data sets need to be displayed
OpenSource solutions:
http://binarymuse.github.io/ngInfiniteScroll/
http://blog.stackfull.com/2013/02/AngularJS-virtual-scrolling-part-1/
DEMO / DEMO (with virtual scroll)
1. View watches / data bindings
2. What you see is what you show
3. The risk of polluting scopes
4. Core directives to avoid
5. Splitting the page
6. Miscellaneous
7. Limits
3. The risk of polluting scopes
✈ DOM / SCOPES
(1) relying on multiple $rootScope and appCtrl functions may slow down the $digest
SOLUTION: try to avoid polluting $rootScope/appCtrl/* scopes
angular.module('codecamp').service('appInit',[
'$rootScope',function($rootScope){
'usestrict';
$rootScope.computeStuff=function(){...};
$rootScope.getData=function(){...};
$rootScope.i18n=function(){...};
$rootScope.manageAppStates=function(){...};
$rootScope.manageFormatters=function(){...};
//...andsoforth
});
?
- dispatch to specialized services/factories/filters/*
... and have some privacy in all scopes
angular.module('codecamp').controller('testCtrl',[
'$scope',function($scope){
'usestrict';
$scope._privateMethod=function(){};
functionnotRecommended(){
//...
}
});
?
1. View watches / data bindings
2. What you see is what you show
3. The risk of polluting scopes
4. Core directives to avoid
5. Splitting the page
6. Miscellaneous
7. Limits
4. Core directives to avoid
ALL of them
... right
Remember what we've said earlier?
"more of 2000 watchers can lag the UI" (angular-tips.com)
varngEventDirectives={};forEach(
'clickdblclickmousedownmouseupmouseoverblur
mouseoutmousemovemouseentermouseleavecopy
keydownkeyupkeypresssubmitfocuscutpaste'
.split(''),function(name){//[...]
returnfunction(scope,element,attr){//LINK
element.on(lowercase(name),function(event){
//scope.$apply=>$rootScope.$apply
scope.$apply(function(){
fn(scope,{$event:event});
});
//[...]
?
SOURCE: github.com/angular/angular.js/blob/
master/src/ng/directive/ngEventDirs.js#L41
Does that really matter?
video not displayable
Quad core, 8 GB of RAM, Win7
Seems so...
video not displayable
SOLUTION: write custom directive(s), catch the events you need and...
.directive('customMouseEnter',[
function(){
'usestrict';
return{
restrict:'A',
link:function(scope,elem,attrs){
varfName=attrs.customMouseEnter,
func=function(ev){
scope[fName](ev);
};
elem.on('mouseenter',func);
scope.$on('$destroy',function(){
elem.off('mouseenter',func);
});
//[...]
?
...trigger local $digests (DEMO $digest over $apply)
//TEMPLATE
<trcustom-mouse-enter="ctrlMouseLeave">
//CONTROLLER/DIRECTIVE
scope.mouseLeave=function(ev){
//highlight,etc
//$digest()onlyonthescopeyouneed
scope.$digest();
};
?
Seems to be pretty common in the community
http://stackoverflow.com/questions/18421732/angularjs-how-to-override-directive-ngclick
http://briantford.com/blog/angular-hacking-core
(★) if you actually override default directives, remember to set a higher priority
1. View watches / data bindings
2. What you see is what you show
3. The risk of polluting scopes
4. Core directives to avoid
5. Splitting the page
6. Miscellaneous
7. Limits
5. Splitting the page
identify what is shareable and what is not
avoid splitting the page in too many sub-components
design your components in a blackbox manner
1. View watches / data bindings
2. What you see is what you show
3. The risk of polluting scopes
4. Core directives to avoid
5. Splitting the page
6. Miscellaneous
7. Limits
6. Miscenallaneous
(1) evalAsync(f) over $timeout(f)
More: http://www.bennadel.com/blog/2605-scope-evalasync-vs-timeout-in-angularjs.htm
(2) Watch out for external components performance and their usage
We had a problem with Moment.JS library (20% of the page load time, according to Chrome
Profiler)
(3) $eval your code from time to time - PERF wise
Batarang (identify $watchers), Chrome Profiler (memory, performance), performance.now()
(BONUS) demythify events
$emit / $broadcast (1)
SOURCE: jsperf.com/rootscope-emit-vs-rootscope-broadcast/24
$emit / $broadcast (2)
SOURCE: jsperf.com/rootscope-emit-vs-rootscope-broadcast/25
Ok... but why?
AngularJS 1.2.6 and below ▶ 12-15x difference
AngularJS 1.2.7+ ▶ 1.1x difference
"limit propagation of $broadcast to scopes that have listeners for the event"
(github.com/angular/angular.js/blob/master/CHANGELOG.md#performance-improvements-3)
RECAP: Common sense still says we should use them according to their design
1. View watches / data bindings
2. What you see is what you show
3. The risk of polluting scopes
4. Core directives to avoid
5. Splitting the page
6. Miscellaneous
7. Limits
7. Limits
"you quickly reach the end of what Angular can do for you when it comes to structuring
applications, at which point the community fragments transform to best practices, and few people
have figured out how to write large-scale Angular apps" (EmberJS core member)
Technical limits
1. + 2.000 dynamic elements on the screen
2. + 3.000 watchers
3. real time apps, where data changes very often
(★) depending on the device
Some apps examples:
stocks exchange
google maps
office apps
OUTPUT: screen flickering, low UX, unresponsive screens
And there's nothing you can do about it... except rewriting it in a lightweight framework
1. View watches / data bindings
2. What you see is what you show
3. The risk of polluting scopes
4. Core directives to avoid
5. Splitting the page
6. Miscellaneous
7. Limits
Recap? (1)
(1) be aware of too many data bindings (bindonce)
(2) try to minimize the number of $digest cycles
(3) have pre-computed values at template level
(4) display only the visible elements (virtual scroll)
Recap? (2)
(5) be aware of core directives PERF problems
(6) don't pollute your scopes and make them TDD friendly
(7) watch out for external components (angular or non-angular) performance
What's next?
it's a good habit to think PERF (pre-$compile the code in your head)
don't assume the frameworks are fast, whatever you may write
watch out for memory leaks
REMINDER: AngularJS is quite easy, just try it!
... and last but not least important: find a company that would allow you to grow your skills!
Q / A

More Related Content

What's hot

Ionic으로 모바일앱 만들기 #4
Ionic으로 모바일앱 만들기 #4Ionic으로 모바일앱 만들기 #4
Ionic으로 모바일앱 만들기 #4성일 한
 
Security testing of YUI powered applications
Security testing of YUI powered applicationsSecurity testing of YUI powered applications
Security testing of YUI powered applicationsdimisec
 
From Hacker to Programmer (w/ Webpack, Babel and React)
From Hacker to Programmer (w/ Webpack, Babel and React)From Hacker to Programmer (w/ Webpack, Babel and React)
From Hacker to Programmer (w/ Webpack, Babel and React)Joseph Chiang
 
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...Christian Janz
 
Creating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todayCreating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todaygerbille
 
Getting touchy - an introduction to touch events / Web Standards Days / Mosco...
Getting touchy - an introduction to touch events / Web Standards Days / Mosco...Getting touchy - an introduction to touch events / Web Standards Days / Mosco...
Getting touchy - an introduction to touch events / Web Standards Days / Mosco...Patrick Lauke
 
Building a js widget
Building a js widgetBuilding a js widget
Building a js widgetTudor Barbu
 
Angular JS blog tutorial
Angular JS blog tutorialAngular JS blog tutorial
Angular JS blog tutorialClaude Tech
 
A Gentle Introduction to Angular Schematics - Angular SF 2019
A Gentle Introduction to Angular Schematics - Angular SF 2019A Gentle Introduction to Angular Schematics - Angular SF 2019
A Gentle Introduction to Angular Schematics - Angular SF 2019Matt Raible
 
Django + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoDjango + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoJavier Abadía
 
Enjoy the vue.js
Enjoy the vue.jsEnjoy the vue.js
Enjoy the vue.jsTechExeter
 
Vue routing tutorial getting started with vue router
Vue routing tutorial getting started with vue routerVue routing tutorial getting started with vue router
Vue routing tutorial getting started with vue routerKaty Slemon
 
A Gentle Introduction to Angular Schematics - Devoxx Belgium 2019
A Gentle Introduction to Angular Schematics - Devoxx Belgium 2019A Gentle Introduction to Angular Schematics - Devoxx Belgium 2019
A Gentle Introduction to Angular Schematics - Devoxx Belgium 2019Matt Raible
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJsTudor Barbu
 
HTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymoreHTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymoreRemy Sharp
 
Hybrid Apps (Native + Web) via QtWebKit
Hybrid Apps (Native + Web) via QtWebKitHybrid Apps (Native + Web) via QtWebKit
Hybrid Apps (Native + Web) via QtWebKitAriya Hidayat
 

What's hot (20)

Ionic으로 모바일앱 만들기 #4
Ionic으로 모바일앱 만들기 #4Ionic으로 모바일앱 만들기 #4
Ionic으로 모바일앱 만들기 #4
 
Security testing of YUI powered applications
Security testing of YUI powered applicationsSecurity testing of YUI powered applications
Security testing of YUI powered applications
 
From Hacker to Programmer (w/ Webpack, Babel and React)
From Hacker to Programmer (w/ Webpack, Babel and React)From Hacker to Programmer (w/ Webpack, Babel and React)
From Hacker to Programmer (w/ Webpack, Babel and React)
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...
Zukunftssichere Anwendungen mit AngularJS 1.x entwickeln (GDG DevFest Karlsru...
 
Creating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of todayCreating the interfaces of the future with the APIs of today
Creating the interfaces of the future with the APIs of today
 
Symfony2 and AngularJS
Symfony2 and AngularJSSymfony2 and AngularJS
Symfony2 and AngularJS
 
Vuex
VuexVuex
Vuex
 
Getting touchy - an introduction to touch events / Web Standards Days / Mosco...
Getting touchy - an introduction to touch events / Web Standards Days / Mosco...Getting touchy - an introduction to touch events / Web Standards Days / Mosco...
Getting touchy - an introduction to touch events / Web Standards Days / Mosco...
 
Building a js widget
Building a js widgetBuilding a js widget
Building a js widget
 
Angular JS blog tutorial
Angular JS blog tutorialAngular JS blog tutorial
Angular JS blog tutorial
 
A Gentle Introduction to Angular Schematics - Angular SF 2019
A Gentle Introduction to Angular Schematics - Angular SF 2019A Gentle Introduction to Angular Schematics - Angular SF 2019
A Gentle Introduction to Angular Schematics - Angular SF 2019
 
Django + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoDjango + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar Django
 
Enjoy the vue.js
Enjoy the vue.jsEnjoy the vue.js
Enjoy the vue.js
 
2021laravelconftwslides11
2021laravelconftwslides112021laravelconftwslides11
2021laravelconftwslides11
 
Vue routing tutorial getting started with vue router
Vue routing tutorial getting started with vue routerVue routing tutorial getting started with vue router
Vue routing tutorial getting started with vue router
 
A Gentle Introduction to Angular Schematics - Devoxx Belgium 2019
A Gentle Introduction to Angular Schematics - Devoxx Belgium 2019A Gentle Introduction to Angular Schematics - Devoxx Belgium 2019
A Gentle Introduction to Angular Schematics - Devoxx Belgium 2019
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
 
HTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymoreHTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymore
 
Hybrid Apps (Native + Web) via QtWebKit
Hybrid Apps (Native + Web) via QtWebKitHybrid Apps (Native + Web) via QtWebKit
Hybrid Apps (Native + Web) via QtWebKit
 

Similar to Dragos Rusu - Angular JS - Overcoming Performance Issues - CodeCamp-10-may-2014

Angular js mobile jsday 2014 - Verona 14 may
Angular js mobile   jsday 2014 - Verona 14 mayAngular js mobile   jsday 2014 - Verona 14 may
Angular js mobile jsday 2014 - Verona 14 mayLuciano Amodio
 
High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2Niti Chotkaew
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax ApplicationsJulien Lecomte
 
Web Applications with AngularJS
Web Applications with AngularJSWeb Applications with AngularJS
Web Applications with AngularJSPhilipp Burgmer
 
Leveraging the Power of Custom Elements in Gutenberg
Leveraging the Power of Custom Elements in GutenbergLeveraging the Power of Custom Elements in Gutenberg
Leveraging the Power of Custom Elements in GutenbergFelix Arntz
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest servicesIoan Eugen Stan
 
Considerations with Writing JavaScript in your DotNetNuke site
Considerations with Writing JavaScript in your DotNetNuke siteConsiderations with Writing JavaScript in your DotNetNuke site
Considerations with Writing JavaScript in your DotNetNuke siteEngage Software
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 
From Monolith to Modules - breaking apart a one size fits all product into mo...
From Monolith to Modules - breaking apart a one size fits all product into mo...From Monolith to Modules - breaking apart a one size fits all product into mo...
From Monolith to Modules - breaking apart a one size fits all product into mo...Robert Munteanu
 
node.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang Yoonnode.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang YoonJesang Yoon
 
Top 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppTop 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppKaty Slemon
 
Modern Web Technologies
Modern Web TechnologiesModern Web Technologies
Modern Web TechnologiesPerttu Myry
 
Modular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJSModular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJSGunnar Hillert
 
Spring Boot and Microservices
Spring Boot and MicroservicesSpring Boot and Microservices
Spring Boot and Microservicesseges
 
Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)
Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)
Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)Christian Catalan
 
Ionic framework one day training
Ionic framework one day trainingIonic framework one day training
Ionic framework one day trainingTroy Miles
 
CloudStack UI
CloudStack UICloudStack UI
CloudStack UIShapeBlue
 
Bitworks CloudStack UI - CSEUUG 08 August 2017
Bitworks CloudStack UI - CSEUUG 08 August 2017Bitworks CloudStack UI - CSEUUG 08 August 2017
Bitworks CloudStack UI - CSEUUG 08 August 2017Ivan Kudryavtsev
 
"Micro-frontends: Scalable and Modular Frontend in Parimatch Tech", Kyrylo Ai...
"Micro-frontends: Scalable and Modular Frontend in Parimatch Tech", Kyrylo Ai..."Micro-frontends: Scalable and Modular Frontend in Parimatch Tech", Kyrylo Ai...
"Micro-frontends: Scalable and Modular Frontend in Parimatch Tech", Kyrylo Ai...Fwdays
 

Similar to Dragos Rusu - Angular JS - Overcoming Performance Issues - CodeCamp-10-may-2014 (20)

Angular js mobile jsday 2014 - Verona 14 may
Angular js mobile   jsday 2014 - Verona 14 mayAngular js mobile   jsday 2014 - Verona 14 may
Angular js mobile jsday 2014 - Verona 14 may
 
High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 
Web Applications with AngularJS
Web Applications with AngularJSWeb Applications with AngularJS
Web Applications with AngularJS
 
micro-frontends-with-vuejs
micro-frontends-with-vuejsmicro-frontends-with-vuejs
micro-frontends-with-vuejs
 
Leveraging the Power of Custom Elements in Gutenberg
Leveraging the Power of Custom Elements in GutenbergLeveraging the Power of Custom Elements in Gutenberg
Leveraging the Power of Custom Elements in Gutenberg
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest services
 
Considerations with Writing JavaScript in your DotNetNuke site
Considerations with Writing JavaScript in your DotNetNuke siteConsiderations with Writing JavaScript in your DotNetNuke site
Considerations with Writing JavaScript in your DotNetNuke site
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
From Monolith to Modules - breaking apart a one size fits all product into mo...
From Monolith to Modules - breaking apart a one size fits all product into mo...From Monolith to Modules - breaking apart a one size fits all product into mo...
From Monolith to Modules - breaking apart a one size fits all product into mo...
 
node.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang Yoonnode.js 실무 - node js in practice by Jesang Yoon
node.js 실무 - node js in practice by Jesang Yoon
 
Top 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular AppTop 7 Angular Best Practices to Organize Your Angular App
Top 7 Angular Best Practices to Organize Your Angular App
 
Modern Web Technologies
Modern Web TechnologiesModern Web Technologies
Modern Web Technologies
 
Modular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJSModular Test-driven SPAs with Spring and AngularJS
Modular Test-driven SPAs with Spring and AngularJS
 
Spring Boot and Microservices
Spring Boot and MicroservicesSpring Boot and Microservices
Spring Boot and Microservices
 
Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)
Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)
Testing Vue Apps with Cypress.io (STLJS Meetup April 2018)
 
Ionic framework one day training
Ionic framework one day trainingIonic framework one day training
Ionic framework one day training
 
CloudStack UI
CloudStack UICloudStack UI
CloudStack UI
 
Bitworks CloudStack UI - CSEUUG 08 August 2017
Bitworks CloudStack UI - CSEUUG 08 August 2017Bitworks CloudStack UI - CSEUUG 08 August 2017
Bitworks CloudStack UI - CSEUUG 08 August 2017
 
"Micro-frontends: Scalable and Modular Frontend in Parimatch Tech", Kyrylo Ai...
"Micro-frontends: Scalable and Modular Frontend in Parimatch Tech", Kyrylo Ai..."Micro-frontends: Scalable and Modular Frontend in Parimatch Tech", Kyrylo Ai...
"Micro-frontends: Scalable and Modular Frontend in Parimatch Tech", Kyrylo Ai...
 

More from Codecamp Romania

Cezar chitac the edge of experience
Cezar chitac   the edge of experienceCezar chitac   the edge of experience
Cezar chitac the edge of experienceCodecamp Romania
 
Business analysis techniques exercise your 6-pack
Business analysis techniques   exercise your 6-packBusiness analysis techniques   exercise your 6-pack
Business analysis techniques exercise your 6-packCodecamp Romania
 
Bpm company code camp - configuration or coding with pega
Bpm company   code camp - configuration or coding with pegaBpm company   code camp - configuration or coding with pega
Bpm company code camp - configuration or coding with pegaCodecamp Romania
 
Andrei prisacaru takingtheunitteststothedatabase
Andrei prisacaru takingtheunitteststothedatabaseAndrei prisacaru takingtheunitteststothedatabase
Andrei prisacaru takingtheunitteststothedatabaseCodecamp Romania
 
2015 dan ardelean develop for windows 10
2015 dan ardelean   develop for windows 10 2015 dan ardelean   develop for windows 10
2015 dan ardelean develop for windows 10 Codecamp Romania
 
The case for continuous delivery
The case for continuous deliveryThe case for continuous delivery
The case for continuous deliveryCodecamp Romania
 
Stefan stolniceanu spritekit, 2 d or not 2d
Stefan stolniceanu   spritekit, 2 d or not 2dStefan stolniceanu   spritekit, 2 d or not 2d
Stefan stolniceanu spritekit, 2 d or not 2dCodecamp Romania
 
Sizing epics tales from an agile kingdom
Sizing epics   tales from an agile kingdomSizing epics   tales from an agile kingdom
Sizing epics tales from an agile kingdomCodecamp Romania
 
Raluca butnaru corina cilibiu the unknown universe of a product and the cer...
Raluca butnaru corina cilibiu   the unknown universe of a product and the cer...Raluca butnaru corina cilibiu   the unknown universe of a product and the cer...
Raluca butnaru corina cilibiu the unknown universe of a product and the cer...Codecamp Romania
 
Parallel & async processing using tpl dataflow
Parallel & async processing using tpl dataflowParallel & async processing using tpl dataflow
Parallel & async processing using tpl dataflowCodecamp Romania
 
Material design screen transitions in android
Material design screen transitions in androidMaterial design screen transitions in android
Material design screen transitions in androidCodecamp Romania
 
Kickstart your own freelancing career
Kickstart your own freelancing careerKickstart your own freelancing career
Kickstart your own freelancing careerCodecamp Romania
 
Ionut grecu the soft stuff is the hard stuff. the agile soft skills toolkit
Ionut grecu   the soft stuff is the hard stuff. the agile soft skills toolkitIonut grecu   the soft stuff is the hard stuff. the agile soft skills toolkit
Ionut grecu the soft stuff is the hard stuff. the agile soft skills toolkitCodecamp Romania
 
Diana antohi me against myself or how to fail and move forward
Diana antohi   me against myself  or how to fail  and move forwardDiana antohi   me against myself  or how to fail  and move forward
Diana antohi me against myself or how to fail and move forwardCodecamp Romania
 

More from Codecamp Romania (20)

Cezar chitac the edge of experience
Cezar chitac   the edge of experienceCezar chitac   the edge of experience
Cezar chitac the edge of experience
 
Cloud powered search
Cloud powered searchCloud powered search
Cloud powered search
 
Ccp
CcpCcp
Ccp
 
Business analysis techniques exercise your 6-pack
Business analysis techniques   exercise your 6-packBusiness analysis techniques   exercise your 6-pack
Business analysis techniques exercise your 6-pack
 
Bpm company code camp - configuration or coding with pega
Bpm company   code camp - configuration or coding with pegaBpm company   code camp - configuration or coding with pega
Bpm company code camp - configuration or coding with pega
 
Andrei prisacaru takingtheunitteststothedatabase
Andrei prisacaru takingtheunitteststothedatabaseAndrei prisacaru takingtheunitteststothedatabase
Andrei prisacaru takingtheunitteststothedatabase
 
Agility and life
Agility and lifeAgility and life
Agility and life
 
2015 dan ardelean develop for windows 10
2015 dan ardelean   develop for windows 10 2015 dan ardelean   develop for windows 10
2015 dan ardelean develop for windows 10
 
The bigrewrite
The bigrewriteThe bigrewrite
The bigrewrite
 
The case for continuous delivery
The case for continuous deliveryThe case for continuous delivery
The case for continuous delivery
 
Stefan stolniceanu spritekit, 2 d or not 2d
Stefan stolniceanu   spritekit, 2 d or not 2dStefan stolniceanu   spritekit, 2 d or not 2d
Stefan stolniceanu spritekit, 2 d or not 2d
 
Sizing epics tales from an agile kingdom
Sizing epics   tales from an agile kingdomSizing epics   tales from an agile kingdom
Sizing epics tales from an agile kingdom
 
Scale net apps in aws
Scale net apps in awsScale net apps in aws
Scale net apps in aws
 
Raluca butnaru corina cilibiu the unknown universe of a product and the cer...
Raluca butnaru corina cilibiu   the unknown universe of a product and the cer...Raluca butnaru corina cilibiu   the unknown universe of a product and the cer...
Raluca butnaru corina cilibiu the unknown universe of a product and the cer...
 
Parallel & async processing using tpl dataflow
Parallel & async processing using tpl dataflowParallel & async processing using tpl dataflow
Parallel & async processing using tpl dataflow
 
Material design screen transitions in android
Material design screen transitions in androidMaterial design screen transitions in android
Material design screen transitions in android
 
Kickstart your own freelancing career
Kickstart your own freelancing careerKickstart your own freelancing career
Kickstart your own freelancing career
 
Ionut grecu the soft stuff is the hard stuff. the agile soft skills toolkit
Ionut grecu   the soft stuff is the hard stuff. the agile soft skills toolkitIonut grecu   the soft stuff is the hard stuff. the agile soft skills toolkit
Ionut grecu the soft stuff is the hard stuff. the agile soft skills toolkit
 
Ecma6 in the wild
Ecma6 in the wildEcma6 in the wild
Ecma6 in the wild
 
Diana antohi me against myself or how to fail and move forward
Diana antohi   me against myself  or how to fail  and move forwardDiana antohi   me against myself  or how to fail  and move forward
Diana antohi me against myself or how to fail and move forward
 

Recently uploaded

Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
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
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
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
 
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
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
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
 
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
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 

Recently uploaded (20)

Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
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
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
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
 
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
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
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
 
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...
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 

Dragos Rusu - Angular JS - Overcoming Performance Issues - CodeCamp-10-may-2014

  • 1. AngularJS. Performance & Limits. Dragos Rusu - CodeCamp Iasi 2014 (dragos.rusu@bytex.ro)
  • 2. Our story From "We have to rethink this whole module, remove time navigation... it's just too sluggish." ★ to "It's awesome, really fast, it's like going from night to day!" ★ (★) SOFTVISION customer
  • 3. A few words about me Dragos Rusu @ SOFTVISION WEB/ZEND ENGINEER since 2007 (backend, frontend) ARTICLE WRITER (PHP Architect) PROJECTS: platforms for airlines (Cathay Pacific, Singapore Airlines, Air Berlin), tourism agencies, home automation and security, agriculture
  • 4. We will discuss about... 1. View watches / data bindings 2. What you see is what you show 3. The risk of polluting scopes 4. Core directives to avoid 5. Splitting the page 6. Miscellaneous 7. Limits Q / A
  • 5. disclaimer PERFORMANCE principles for heavy apps (+500 man days) * many items are not covered here. * code samples - only in AngularJS never used AngularJS before? no problem, principles are general, yet the solutions are particular.
  • 7. 1. View watches / data bindings
  • 8. GENERAL CONTEXT "more of 2000 watchers can lag the UI" (angular-tips.com) "the expressions in curly braces denote bindings" ({{ ... }}) (docs.angularjs.org) "AngularJS internally creates a $watch for each ng-* directive" (github.com/Pasvaz/bindonce) "ngRepeat directive instantiates a template once per item [...] each template instance gets its own scope" (docs.angularjs.org)
  • 9. Ok... but why would I be counting watches?
  • 10.
  • 11. Every watcher is run at the digest cycle. The digest cycle is repeated until none of the results has changed value (Brian Ford - AngularJS contributor)
  • 12. ✈ A peak into AngularJS source code $apply:function(expr){ try{ beginPhase('$apply'); returnthis.$eval(expr); }catch(e){$exceptionHandler(e); }finally{ clearPhase(); try{ $rootScope.$digest();//Ouhmy... //[...] ? https://github.com/angular/angular.js/blob/ master/src/ng/rootScope.js#L943
  • 13.
  • 14.
  • 15.
  • 16.
  • 17. (1) double-binding creates tons of listeners
  • 18. SOLUTION: Whenever feasible, use single-binding solutions double binding DEMO / bindonce DEMO
  • 19. Why? Is double-binding slow? Not quite. The AngularJS way of implementing it is slow ($dirty flags instead of observable properties). pssst: ECMA6: Object.observe()
  • 21. (2) direct function calls from templates are called very often SOLUTION: pre-compute the values to shown in the view model (default values, totals, etc) <ul> <ling-repeat="iteminitems"> //{{item.name}}({{computeTotal(item)}}) {{item.name}}({{item.computedTotal}}) </li> </ul> ?
  • 22. EXAMPLE vatTotal will be recomputed on each scope $digest, regardless if the values that vatTotal() depend on are changed or not (DEMO) //...controller... $scope.vat=24;//% $scope.vatTotal=function(){ return( $scope.data.item.total* (1+$scope.vat/100) ); }; //...template... {{vatTotal()}} ?
  • 23. (3) iterating over large data sets slows down the page SOLUTION: create a lightweight iterable view model angular.module('codecamp').controller('testCtrl',[ '$scope','dm','$q',function($scope,dm,$q){ 'usestrict'; $scope._init=function(){ $scope.testViewModel={}; $q.all([dm.getData1(),dm.getData2()]) .then(function(response){ $scope.computeViewModel(response.data); } ); }; $scope._init(); } ); ?
  • 24. (4) ng-repeat extra DOM manipulations SOLUTION: ng-repeat with track by id (DEMO) <ul> <ling-repeat="iteminitemstrackbyitem.id"> {{item.name}} </li> </ul> ?
  • 25. (5) filters are called very often SOLUTION: lightweight quasi-independent filters <span>{{value}}</span> <ul> <ling-repeat="iteminitems"> {{item.name|heavyFilteritem.value,$index}} </li> </ul> ? WARNING: avoid touching DOM in filters and watches
  • 26. (6) multiple recursive $watch might cause page flickering SOLUTION: try to avoid recursive watch, where feasible $scope.$watch('model.items', function(newValue,oldValue){ //dosmth },recursive=true); ); ?
  • 27. (7) direct DOM watch functions might slow down the page SOLUTION: try to avoid complex valueExpression, where feasible (use the data model instead) //DirectiveLINKfunction link:function($scope,$el,$attrs){ $scope.$watch( function(){return$el[0].childNodes.length;}, function(newValue,oldValue){} ); } ? SOURCE: stackoverflow.com/questions/21332671
  • 28. 1. View watches / data bindings 2. What you see is what you show 3. The risk of polluting scopes 4. Core directives to avoid 5. Splitting the page 6. Miscellaneous 7. Limits
  • 29. 2. What you see is what you show
  • 30. ng-if vs. ng-show (1) ng-hide and ng-show makes no speed difference (DEMO) <ulng-hide="hideCondition"> <ling-repeat="iteminitems"> {{item.value}} </li> </ul> ?
  • 31. ng-if vs. ng-show (2) ng-if/ng-switch might make a difference on more content (e.g. tabbed page) <ulng-if="displayCondition"> //CONTENT </ul> ? * fewer bindings * fewer linkers called at startup
  • 32. remove non-visible elements in the scroll (1) one easy way would be PAGINATION doesn't always apply though...
  • 33. remove non-visible elements in the scroll (2) DISPLAY elements, but ONLY THE VISIBLE ones known as the VIRTUAL/INFINITE SCROLLING problem
  • 34. remove non-visible elements in the scroll (3) usually occurs when large data sets need to be displayed OpenSource solutions: http://binarymuse.github.io/ngInfiniteScroll/ http://blog.stackfull.com/2013/02/AngularJS-virtual-scrolling-part-1/ DEMO / DEMO (with virtual scroll)
  • 35. 1. View watches / data bindings 2. What you see is what you show 3. The risk of polluting scopes 4. Core directives to avoid 5. Splitting the page 6. Miscellaneous 7. Limits
  • 36. 3. The risk of polluting scopes
  • 37. ✈ DOM / SCOPES
  • 38.
  • 39.
  • 40. (1) relying on multiple $rootScope and appCtrl functions may slow down the $digest SOLUTION: try to avoid polluting $rootScope/appCtrl/* scopes angular.module('codecamp').service('appInit',[ '$rootScope',function($rootScope){ 'usestrict'; $rootScope.computeStuff=function(){...}; $rootScope.getData=function(){...}; $rootScope.i18n=function(){...}; $rootScope.manageAppStates=function(){...}; $rootScope.manageFormatters=function(){...}; //...andsoforth }); ? - dispatch to specialized services/factories/filters/*
  • 41. ... and have some privacy in all scopes angular.module('codecamp').controller('testCtrl',[ '$scope',function($scope){ 'usestrict'; $scope._privateMethod=function(){}; functionnotRecommended(){ //... } }); ?
  • 42. 1. View watches / data bindings 2. What you see is what you show 3. The risk of polluting scopes 4. Core directives to avoid 5. Splitting the page 6. Miscellaneous 7. Limits
  • 43. 4. Core directives to avoid
  • 45. Remember what we've said earlier? "more of 2000 watchers can lag the UI" (angular-tips.com)
  • 47.
  • 48. Does that really matter? video not displayable Quad core, 8 GB of RAM, Win7
  • 49. Seems so... video not displayable
  • 50. SOLUTION: write custom directive(s), catch the events you need and... .directive('customMouseEnter',[ function(){ 'usestrict'; return{ restrict:'A', link:function(scope,elem,attrs){ varfName=attrs.customMouseEnter, func=function(ev){ scope[fName](ev); }; elem.on('mouseenter',func); scope.$on('$destroy',function(){ elem.off('mouseenter',func); }); //[...] ?
  • 51. ...trigger local $digests (DEMO $digest over $apply) //TEMPLATE <trcustom-mouse-enter="ctrlMouseLeave"> //CONTROLLER/DIRECTIVE scope.mouseLeave=function(ev){ //highlight,etc //$digest()onlyonthescopeyouneed scope.$digest(); }; ?
  • 52. Seems to be pretty common in the community http://stackoverflow.com/questions/18421732/angularjs-how-to-override-directive-ngclick http://briantford.com/blog/angular-hacking-core (★) if you actually override default directives, remember to set a higher priority
  • 53. 1. View watches / data bindings 2. What you see is what you show 3. The risk of polluting scopes 4. Core directives to avoid 5. Splitting the page 6. Miscellaneous 7. Limits
  • 55. identify what is shareable and what is not avoid splitting the page in too many sub-components design your components in a blackbox manner
  • 56. 1. View watches / data bindings 2. What you see is what you show 3. The risk of polluting scopes 4. Core directives to avoid 5. Splitting the page 6. Miscellaneous 7. Limits
  • 58. (1) evalAsync(f) over $timeout(f) More: http://www.bennadel.com/blog/2605-scope-evalasync-vs-timeout-in-angularjs.htm
  • 59. (2) Watch out for external components performance and their usage We had a problem with Moment.JS library (20% of the page load time, according to Chrome Profiler)
  • 60. (3) $eval your code from time to time - PERF wise Batarang (identify $watchers), Chrome Profiler (memory, performance), performance.now()
  • 62. $emit / $broadcast (1) SOURCE: jsperf.com/rootscope-emit-vs-rootscope-broadcast/24
  • 63. $emit / $broadcast (2) SOURCE: jsperf.com/rootscope-emit-vs-rootscope-broadcast/25
  • 64. Ok... but why? AngularJS 1.2.6 and below ▶ 12-15x difference AngularJS 1.2.7+ ▶ 1.1x difference "limit propagation of $broadcast to scopes that have listeners for the event" (github.com/angular/angular.js/blob/master/CHANGELOG.md#performance-improvements-3) RECAP: Common sense still says we should use them according to their design
  • 65. 1. View watches / data bindings 2. What you see is what you show 3. The risk of polluting scopes 4. Core directives to avoid 5. Splitting the page 6. Miscellaneous 7. Limits
  • 67. "you quickly reach the end of what Angular can do for you when it comes to structuring applications, at which point the community fragments transform to best practices, and few people have figured out how to write large-scale Angular apps" (EmberJS core member)
  • 68. Technical limits 1. + 2.000 dynamic elements on the screen 2. + 3.000 watchers 3. real time apps, where data changes very often (★) depending on the device
  • 69. Some apps examples: stocks exchange google maps office apps OUTPUT: screen flickering, low UX, unresponsive screens And there's nothing you can do about it... except rewriting it in a lightweight framework
  • 70. 1. View watches / data bindings 2. What you see is what you show 3. The risk of polluting scopes 4. Core directives to avoid 5. Splitting the page 6. Miscellaneous 7. Limits
  • 71. Recap? (1) (1) be aware of too many data bindings (bindonce) (2) try to minimize the number of $digest cycles (3) have pre-computed values at template level (4) display only the visible elements (virtual scroll)
  • 72. Recap? (2) (5) be aware of core directives PERF problems (6) don't pollute your scopes and make them TDD friendly (7) watch out for external components (angular or non-angular) performance
  • 73. What's next? it's a good habit to think PERF (pre-$compile the code in your head) don't assume the frameworks are fast, whatever you may write watch out for memory leaks REMINDER: AngularJS is quite easy, just try it! ... and last but not least important: find a company that would allow you to grow your skills!
  • 74. Q / A