Boost Angular Application Performance

Application development

  • We start with small application
  • keeps growing with time as features and modules added
  • wrote a code without studying best practices or framework / library limitation.
  • Such may exploit after sometime
  • At the end any performance issue impact Software Quality
  • End user would not happy.

Performance improvement might lead to rework whole feature or module

Performance is an important aspect

..Anonymous

S/W Performance Impact

  • Quality
  • User happiness
  • Customer may try alternative
  • etc..

Pankaj Parkar

Senior Software Engineer

TSS Consultancy PVT LTD

  • Microsoft MVP (since July 2016)
  • Community Contributor
  • Daily Code in .Net and Angular
  • Stackoverflow Topuser

Navbar component

Search component

Input 

+

Client-list component

Item

Item

.

.

.

Input 

+

Client-list component

Item

Item

.

.

.

App Component

Text

Navbar Component

Search Component

Customer-list Component

Change Detection

Mechanism to analyse the changes and reflect them on the view "

Techniques

  • Virtual DOM

  • Dirty checking

Virtual DOM

  • State render JavaScript object

  • then Last states are compared to detect difference

  • difference applied on the view.

Virtual DOM

App

Todos

Input

Button

Eat

Sleep

App

Todos

Input

Button

Eat

Diff Tree

Dirty Checking

  • Checks for value every time

  • Framework checks for update

  • Update the view

When Dirty Checking Happens?

  • Event callback

  • Network message (XHR's)

  • Timeout / SetInterval callback

//network Call
getDataFromServer()
.then(()=> {
   //state has changed
   detectChanges();
})
//timeout function
setTimeout(()=> {
   //Call change detection
   detectChanges();
}, 5000)
element.addEventListner('click', (event) =>{
   //state could have change
   detectChanges();
});
let detectChanges => () => {
  if(currentState != prevState)
    updateView(currentState);
}

Detect Changes Method

This was how AngularJS do change detection ('Digest Cycle')

  • For Network Call AngularJS used services $http and $resource
  • For setTimetout / setInterval angularjs has $timeout & $interval services.
  • For event callback there are multiple directive like ng-click, ng-focus, ng-mouseover, etc..
  • Apart from this if something gonna happen outside angularjs context they were doing manual `$apply`
  • $apply function responsible to run $digest cycle in angularjs

Angular change detection is smarter

  • ZoneJS to the rescue

  • monkey Patches macrotasks

let originalSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = (data) => {
  //monkey patch code
  if ( URL DOES NOT POINT TO AD SERVER ) {
    return originalSend.apply(this, arguments);
  }

  return false;
};

Zone.afterInvoke()

appliction_ref.ts

appliction_ref.ts

Source: https://github.com/angular/angular/blob/master/packages/core/src/application_ref.ts#L513-L532

Change Detection

There are three change detection strategy.

  1. Default
  2. Detached
  3. OnPush

Change detection fires

CD -> Change Detection

Change detection Default Strategy

@Input() name1

@Input() name2

[name]="name2"

[name]="name1"

name1 = 'Ravi'

name2 = 'Pankaj'

name1 = 'Ravi'

name2 = 'Keerti'

Change detection OnPush Strategy

Detached Change Detection Strategy

  • Run change detection manually
  • Use markForCheck method to enable change detection on component for next cycle of Change detection run.
constructor(
  private cd: ChangeDetectorRef
) {
  cd.detatch();
}

We will cover 9 performance improvement

Before moving ahead analyse the application

1. Component OnPush strategy ChangeDetectionStrategy

2. Don't try to use Angular

for everything

some problems can be solved simple solutions like CSS & HTML or other easiest way.

3. AOT - Prod mode

Angular uses below compilation process

@angular/compiler

  • Converts all component to ngfactory
  • ngfactory has optimised version of the code that you written
  • Browser understand and parse code quickly

Angular

Code

Loaded to browser 

  1. JIT Compilation
  2. AOT compilation

JIT Compilation

Browser use this code

Advantage Of AOT

  • Smaller bundles
  • Template and CSS are inline, which save bunch of server roundtrip
  • Detect template error earlier build time
  • Better security

Recommended to Use CLI

  • Angular CLI takes care of tree shaking
  • Angular 4 has AOT by default Prod mode enabled on production mode CLI

4. Sub-divide Big component to utilize change detection strategy

client-list component

Add customer Name

+

.

.

.

5. Pure pipe 

Angular has two types of Pipe.

  1. Pure Pipe      - They act like pure function
  2. Impure Pipe - There output varies every time
function getNumber(val) {
   return Math.random();
}
function square(val) {
   return val * val;
}

Impure Function

Pure Function

  • Angular has made performance optimisation by storing last return value  (memoization of last value)

+ Memoization

6. Clear observables / cleanup async code in ngOnDestroy lifecycle events.

In case of observable you could think of using async pipe using 

7. Import specific

Don't forget to remove unnecessary  if you're not using it.

8. Never load default route to be loaded lazily

It would tend to load the default module after angular application intialize where as other way would be slightly faster

9. NgFor NgForTrackBy

  • When an item is added, a new instance of the template is added to the DOM.
  • When an item is removed, its template instance is removed from the DOM.
  • When items are reordered, their respective templates are reordered in the DOM.
  • Otherwise, the DOM element for that item will remain the same.

Old

Collection

Brought 

new 

Collection

server

Q & A

References

  • https://addyosmani.com/blog/faster-javascript-memoization/

  • http://jamesknelson.com/5-types-react-application-state/

  • https://www.youtube.com/watch?v=esDKcn_1aic

  • https://github.com/mgechev/angular-performance-checklist

Boost Angular Application Performance

By Pankaj Parkar

Boost Angular Application Performance

Focused on How to improve Angular application performance.

  • 1,205