Slide 1

Slide 1 text

twitter.com/mgechev github.com/mgechev blog.mgechev.com Angular Performance Checklist

Slide 2

Slide 2 text

twitter.com/mgechev twitter.com/mgechev twitter.com/mgechev github.com/mgechev

Slide 3

Slide 3 text

twitter.com/mgechev

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

No content

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

twitter.com/mgechev Runtime Performance

Slide 9

Slide 9 text

twitter.com/mgechev Change Detection

Slide 10

Slide 10 text

twitter.com/mgechev Mechanism for detecting changes which should be reflected in the view

Slide 11

Slide 11 text

twitter.com/mgechev Techniques ‣ Observer pattern ‣ Virtual DOM ‣ Dirty checking

Slide 12

Slide 12 text

twitter.com/mgechev

Slide 13

Slide 13 text

twitter.com/mgechev Observer Pattern ‣ Push based ‣ State triggers an event on change ‣ View handles the event and updates

Slide 14

Slide 14 text

// state.ts class State extends EventEmitter {...} const state = new State({ todos: [] }); state.todos.push('Buy milk'); state.emit(Change) // view.ts class View { // more code update(state) { // visualize todos } } const view = new View(); state.on(Change, _ => view.update(state));

Slide 15

Slide 15 text

// state.ts class State extends EventEmitter {...} const state = new State({ todos: [] }); state.todos.push('Buy milk'); state.emit(Change) // view.ts class View { // more code update(state) { // visualize todos } } const view = new View(); state.on(Change, _ => view.update(state));

Slide 16

Slide 16 text

twitter.com/mgechev Virtual Dom ‣ State renders in a “virtual view” ‣ Diff between the last two versions of the “virtual view” ‣ Diff applied to the view

Slide 17

Slide 17 text

[] State TODOS APP INPUT BUTTON

Slide 18

Slide 18 text

TODOS APP INPUT BUTTON State ['Buy milk']

Slide 19

Slide 19 text

State ['Buy milk'] TODOS APP INPUT BUTTON TODOS APP INPUT BUTTON TODO

Slide 20

Slide 20 text

State ['Buy milk'] TODOS APP INPUT BUTTON TODOS APP INPUT BUTTON TODO

Slide 21

Slide 21 text

State ['Buy milk'] TODOS APP INPUT BUTTON TODO

Slide 22

Slide 22 text

State ['Buy milk'] TODOS APP INPUT BUTTON TODO

Slide 23

Slide 23 text

twitter.com/mgechev Dirty Checking ‣ Pull based ‣ Framework checks for state updates ‣ Framework update the view

Slide 24

Slide 24 text

twitter.com/mgechev Dirty Checking ‣ Pull based ‣ Framework checks for state updates ‣ Framework update the view

Slide 25

Slide 25 text

twitter.com/mgechev When?

Slide 26

Slide 26 text

twitter.com/mgechev Dirty Checking ‣ After each event callback ‣ After each network message ‣ After each timeout callback ‣ …

Slide 27

Slide 27 text

sample.ts fetch(url) .then(r => r.json()) .then(data => { // mutate the state detectChanges(); }); timeout(() => { // mutate the state detectChanges(); }, 1000); btn.addEventListener('click', () => { // mutate the state detectChanges(); }); const detectChanges = _ => { if (state !== prevState) { updateView(state); } };

Slide 28

Slide 28 text

sample.ts fetch(url) .then(r => r.json()) .then(data => { // mutate the state detectChanges(); }); timeout(() => { // mutate the state detectChanges(); }, 1000); btn.addEventListener('click', () => { // mutate the state detectChanges(); }); const detectChanges = _ => { if (state !== prevState) { updateView(state); } };

Slide 29

Slide 29 text

sample.ts fetch(url) .then(r => r.json()) .then(data => { // mutate the state detectChanges(); }); timeout(() => { // mutate the state detectChanges(); }, 1000); btn.addEventListener('click', () => { // mutate the state detectChanges(); }); const detectChanges = _ => { if (state !== prevState) { updateView(state); } };

Slide 30

Slide 30 text

sample.ts fetch(url) .then(r => r.json()) .then(data => { // mutate the state detectChanges(); }); timeout(() => { // mutate the state detectChanges(); }, 1000); btn.addEventListener('click', () => { // mutate the state detectChanges(); }); const detectChanges = _ => { if (state !== prevState) { updateView(state); } };

Slide 31

Slide 31 text

sample.ts fetch(url) .then(r => r.json()) .then(data => { // mutate the state detectChanges(); }); timeout(() => { // mutate the state detectChanges(); }, 1000); btn.addEventListener('click', () => { // mutate the state detectChanges(); }); const detectChanges = _ => { if (state !== prevState) { updateView(state); } };

Slide 32

Slide 32 text

twitter.com/mgechev Zone.js intercepts all tasks and micro tasks

Slide 33

Slide 33 text

zone.ts (pseudo code) https://goo.gl/j1Osvu const orig = Node.prototype.addEventListener; Node.prototype.addEventListener = function (old, f) { let cb = () => { old(); zone.afterInvoke(); }; orig.call(this, cb, f); };

Slide 34

Slide 34 text

... this._zone.onMicrotaskEmpty.subscribe( { next: () => { this._zone.run(() => { this.tick(); }); } } ); ... application_ref.ts

Slide 35

Slide 35 text

application_ref.ts ... tick(): void { ... try { this._views.forEach((view) => view.detectChanges()); if (this._enforceNoNewChanges) { this._views.forEach((view) => view.checkNoChanges()); } } catch (e) { ... } } ...

Slide 36

Slide 36 text

application_ref.ts ... tick(): void { ... try { this._views.forEach((view) => view.detectChanges()); if (this._enforceNoNewChanges) { this._views.forEach((view) => view.checkNoChanges()); } } catch (e) { ... } } ...

Slide 37

Slide 37 text

twitter.com/mgechev APP TODOS TODO INPUT BUTTON

Slide 38

Slide 38 text

twitter.com/mgechev APP TODOS TODO INPUT BUTTON

Slide 39

Slide 39 text

twitter.com/mgechev APP TODOS TODO INPUT BUTTON

Slide 40

Slide 40 text

twitter.com/mgechev APP TODOS TODO INPUT BUTTON

Slide 41

Slide 41 text

twitter.com/mgechev APP TODOS TODO INPUT BUTTON

Slide 42

Slide 42 text

twitter.com/mgechev APP TODOS TODO INPUT BUTTON

Slide 43

Slide 43 text

... ... ...

Slide 44

Slide 44 text

... ... ...

Slide 45

Slide 45 text

... ... ...

Slide 46

Slide 46 text

twitter.com/mgechev We have less than 16.667ms for JavaScript execution

Slide 47

Slide 47 text

twitter.com/mgechev Do not add bindings to heavy computations in the templates Practice #1

Slide 48

Slide 48 text

application_ref.ts ... tick(): void { ... try { this._views.forEach((view) => view.detectChanges()); if (this._enforceNoNewChanges) { this._views.forEach((view) => view.checkNoChanges()); } } catch (e) { ... } } ...

Slide 49

Slide 49 text

circular-update.ts @Component({ selector: 'app-counter', template: '{{counter}}' }) export class CounterComponent { private _counter = 1; get counter() { return this._counter++; } }

Slide 50

Slide 50 text

circular-update.ts @Component({ selector: 'app-counter', template: '{{counter}}' }) export class CounterComponent { private _counter = 1; get counter() { return this._counter++; } }

Slide 51

Slide 51 text

twitter.com/mgechev view.checkNoChanges slows us down in production, at least twice!

Slide 52

Slide 52 text

twitter.com/mgechev Always invoke enableProdMode in our production applications Default behavior for the production builds of Angular CLI, angular seed Practice #2

Slide 53

Slide 53 text

twitter.com/mgechev How Angular Updates The View ‣ Checks for changes in the state ‣ Applies only required updates

Slide 54

Slide 54 text

twitter.com/mgechev Angular generates code for performing change detection and updating the view

Slide 55

Slide 55 text

twitter.com/mgechev Generation Could Be ‣ Runtime, a.k.a. Just-in-Time ‣ Build time, a.k.a. Ahead-of-Time

Slide 56

Slide 56 text

No content

Slide 57

Slide 57 text

twitter.com/mgechev Performing the compilation step runtime (JiT) slows down the initial rendering

Slide 58

Slide 58 text

twitter.com/mgechev Use Ahead-of-Time compilation in production Default behavior for the production builds of Angular CLI, angular seed Practice #3

Slide 59

Slide 59 text

twitter.com/mgechev Use Ahead-of-Time compilation in production Default behavior for the production builds of Angular CLI, angular seed Practice #3 everywhere

Slide 60

Slide 60 text

twitter.com/mgechev The best way to speed-up the change detection is to not perform it at all!

Slide 61

Slide 61 text

twitter.com/mgechev ChangeDetectorRef

Slide 62

Slide 62 text

twitter.com/mgechev ChangeDetectorRef ‣ Detach the change detector ‣ Check for changes manually ‣ Re-attach the change detector Allows us to:

Slide 63

Slide 63 text

@Component({ selector: 'todos-cmp', template: ` ` }) class TodosComponent { items: Todo[] = []; constructor(private ref: ChangeDetectorRef) { ref.detach(); } addItem(item: Todo) { this.items.push(item); this.ref.detectChanges(); } }

Slide 64

Slide 64 text

@Component({ selector: 'todos-cmp', template: ` ` }) class TodosComponent { items: Todo[] = []; constructor(private ref: ChangeDetectorRef) { ref.detach(); } addItem(item: Todo) { this.items.push(item); this.ref.detectChanges(); } }

Slide 65

Slide 65 text

@Component({ selector: 'todos-cmp', template: ` ` }) class TodosComponent { items: Todo[] = []; constructor(private ref: ChangeDetectorRef) { ref.detach(); } addItem(item: Todo) { this.items.push(item); this.ref.detectChanges(); } }

Slide 66

Slide 66 text

twitter.com/mgechev APP TODOS TODO INPUT BUTTON

Slide 67

Slide 67 text

twitter.com/mgechev APP TODOS TODO INPUT BUTTON

Slide 68

Slide 68 text

twitter.com/mgechev APP TODOS TODO INPUT BUTTON

Slide 69

Slide 69 text

twitter.com/mgechev APP TODOS TODO INPUT BUTTON

Slide 70

Slide 70 text

twitter.com/mgechev APP TODOS TODO INPUT BUTTON todos.addItem(todo);

Slide 71

Slide 71 text

twitter.com/mgechev APP TODOS TODO INPUT BUTTON todos.addItem(todo);

Slide 72

Slide 72 text

twitter.com/mgechev APP TODOS TODO INPUT BUTTON TODO todos.addItem(todo);

Slide 73

Slide 73 text

twitter.com/mgechev Useful when… ‣ Show multiple updates in batch ‣ Implement custom change detection logic

Slide 74

Slide 74 text

twitter.com/mgechev Consider manual change detection invocation in case of large state or frequent updates Practice #4

Slide 75

Slide 75 text

twitter.com/mgechev Externalizing the state

Slide 76

Slide 76 text

@Component({ selector: 'todos-cmp', template: `...` }) class TodosComponent { _items: Todo[] = []; constructor(private ref: ChangeDetectorRef) { ref.detach(); } @Input() set items(items: Todo[]) { this._items = items; this.ref.detectChanges(); } get items() { return this._items; } }

Slide 77

Slide 77 text

@Component({ selector: 'todos-cmp', template: `...` }) class TodosComponent { _items: Todo[] = []; constructor(private ref: ChangeDetectorRef) { ref.detach(); } @Input() set items(items: Todo[]) { this._items = items; this.ref.detectChanges(); } get items() { return this._items; } }

Slide 78

Slide 78 text

@Component({ selector: 'todos-cmp', template: `...` }) class TodosComponent { _items: Todo[] = []; constructor(private ref: ChangeDetectorRef) { ref.detach(); } @Input() set items(items: Todo[]) { this._items = items; this.ref.detectChanges(); } get items() { return this._items; } }

Slide 79

Slide 79 text

twitter.com/mgechev Two problems… ‣ Variable could be mutated by other component Change detection won’t work

Slide 80

Slide 80 text

twitter.com/mgechev ParentComponent SiblingComponent TodosComponent const todos = [a, b, c];

Slide 81

Slide 81 text

twitter.com/mgechev ParentComponent SiblingComponent TodosComponent const todos = [a, b, c]; todos

Slide 82

Slide 82 text

twitter.com/mgechev ParentComponent SiblingComponent TodosComponent const todos = [a, b, c]; todos todos todos.push(d);

Slide 83

Slide 83 text

twitter.com/mgechev ParentComponent SiblingComponent TodosComponent const todos = [a, b, c]; todos todos todos.push(d);

Slide 84

Slide 84 text

twitter.com/mgechev Two problems… ‣ Variable could be mutated by other component ‣ Change detection won’t work

Slide 85

Slide 85 text

twitter.com/mgechev ParentComponent SiblingComponent TodosComponent const todos = [a, b, c]; todos.slice();

Slide 86

Slide 86 text

twitter.com/mgechev Immutability

Slide 87

Slide 87 text

@Component({ selector: 'todos-cmp', template: `...` changeDetection: ChangeDetectionStrategy.OnPush }) class TodosComponent { _items: Todo[] = []; constructor(private ref: ChangeDetectorRef) { ref.detach(); } @Input() set items(items: Todo[]) { this._items = items; this.ref.detectChanges(); } get items() { return this._items; } }

Slide 88

Slide 88 text

@Component({ selector: 'todos-cmp', template: `...` changeDetection: ChangeDetectionStrategy.OnPush }) class TodosComponent { _items: Todo[] = []; constructor(private ref: ChangeDetectorRef) { ref.detach(); } @Input() set items(items: Todo[]) { this._items = items; this.ref.detectChanges(); } get items() { return this._items; } }

Slide 89

Slide 89 text

@Component({ selector: 'todos-cmp', template: `...`, changeDetection: ChangeDetectionStrategy.OnPush }) class TodosComponent { _items: Todo[] = []; constructor(private ref: ChangeDetectorRef) { ref.detach(); } @Input() set items(items: Todo[]) { this._items = items; this.ref.detectChanges(); } get items() { return this._items; } }

Slide 90

Slide 90 text

twitter.com/mgechev Externalize the state and use OnPush for skipping CD for component subtrees Practice #5

Slide 91

Slide 91 text

twitter.com/mgechev Pipes

Slide 92

Slide 92 text

twitter.com/mgechev Memoization is a technique used to speed up programs by storing the results of function calls and returning the cached result when the same inputs occur again.

Slide 93

Slide 93 text

twitter.com/mgechev Pure Functions ‣ Same result when invoked with same arguments ‣ Do not have side-effects Can be optimized with memoization because:

Slide 94

Slide 94 text

const fib = n => { if (n === 1 || n === 2) return 1; return fib(n - 1) + fib(n - 2); } @Pipe({ name: 'fib', pure: true }) export FibPipe implements PipeTransform { transform(val: number) { return fib(val); } }

Slide 95

Slide 95 text

const fib = n => { if (n === 1 || n === 2) return 1; return fib(n - 1) + fib(n - 2); } @Pipe({ name: 'fib', pure: true }) export FibPipe implements PipeTransform { transform(val: number) { return fib(val); } }

Slide 96

Slide 96 text

const fib = n => { if (n === 1 || n === 2) return 1; return fib(n - 1) + fib(n - 2); } @Pipe({ name: 'fib', pure: true }) export FibPipe implements PipeTransform { transform(val: number) { return fib(val); } }

Slide 97

Slide 97 text

twitter.com/mgechev Use pure pipes for faster expression evaluation Practice #6

Slide 98

Slide 98 text

twitter.com/mgechev mgv.io/ng-perf-checklist

Slide 99

Slide 99 text

Thank you! twitter.com/mgechev github.com/mgechev blog.mgechev.com twitter.com/mgechev