Every Performance tips for angular app (RunTime Part)
Tags: html, javascript, angular, css
Published: 2020-04-03 13:47:38

---
title: Every Performance tips for angular app (RunTime Part)
published: true
description:
tags: html, javascript, angular, css
series: Angular Performance
---

This is the second part of [Every Performance tips for the angular app](https://dev.to/imm9o/every-performance-tips-for-angular-app-25c4), in this post my primary focus here to list every performance tips about runtime and what to avoid or optimize.

## Avoid render large DOM Tree in views

**The Problem**

A large DOM tree can slow down your page performance in multiple ways:

1. A complex page means more bytes to download.
2. Slower DOM access in JavaScript.
3. Memory performance when select genral selectors like `li`.

**How to enhance ?**

- Use `<ng-container>` The Angular <ng-container> is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.
- Use [Virtual Scrolling](https://material.angular.io/cdk/scrolling/overview), Infinite scroll or Pagination techniques to avoid render large list at once.
- Always use `trackBy` to decrease the number of DOM mutations as you know Manipulating the DOM is an expensive task.

## Optimize template expressions

**The Problem**

Angular executes template expressions after every change detection cycle.

**How to enhance ?**

- Expressions should finish quickly avoid complex expressions.
- Avoid Function Calls and Getters in Views instead use a custom pure pipe.
- Consider caching values by using [pure pipes](https://angular.io/guide/pipes#pure-and-impure-pipes).

## Avoid unnecessary Change Detection (CD)

**The Problem**

On each asynchronous event, Angular performs change detection over the entire component tree. Although the code which detects for changes is optimized for inline-caching, this still can be a heavy computation in complex applications.

**How to enhance?**

- OnPush Change detection stratgy

Unlike the default strategy, which checks a component whenever there’s a change in your app, OnPush change detection reacts only to changes in the @input parameters, or when you manually trigger detection.

```typescript
@Component({
  ...,
  changeDetection: ChangeDetectionStrategy.OnPush
})
```

- Use `detach`ing and `reattach`ing

When we use `deatch` the CD Angular will not perform check for the entire component subtree until it is reattached.

```typescript
export class AComponent {
  constructor(public cd: ChangeDetectorRef) {
    this.cd.detach();
  }
}
```

- Run outside angular

In some cases we want to execute async call without running CD in angular as ui will not be changed, so there is a function called `runOutsideAngular` we can use to run any async function outside angular CD.

```typescript
export class AComponent implements OnDestroy {
  interval = null;
  constructor(private _zone: NgZone) {
    this._zone.runOutsideAngular(() => {
      this.interval = window.setInterval(() => {
        console.log(`Triggers OutsideAngular`);
      }, 10);
    });
  }

  ngOnDestroy() {
    if (this.interval) {
      clearInterval(this.interval);
    }
  }
}
```

## Optimize subscription in Component and Views

**The Problem**

Subscribe to one or more observable can lead to a memory leak as the observable stream is left open.

**How to enhance ?**

- Avoid subscribing to observables from components and instead subscribe to the observables from the template by using [Async pipe](https://angular.io/guide/pipes#the-impure-asyncpipe).
- If you have to subscribe from components consider `unsubscribe` inside [ngOnDestroy](https://angular.io/guide/lifecycle-hooks#ondestroy) lifecycle hooks function.
- Avoid [multi async](https://medium.com/better-programming/let-angular-manage-your-rxjs-subscriptions-better-9243073e94b0) pipe in Views.
- Consider using canceling operators like `takeUntil`, `takeWhile` or `switchMap`.

## Avoid unnecessary emitting inside observable

**The Problem**

Emitting the same value multiple times or emitting unused value inside observable can lead to unnecessary change detection in angular.

**How to enhance ?**

- Use `filter`: Filter items emitted by the source Observable by only emitting those that satisfy a specified predicate.
- Use `throttleTime`: Emits a value from the source Observable, then ignores subsequent source values for duration milliseconds, then repeats this process.
- Use `debounceTime`: Emits a value from the source Observable only after a particular time span has passed without another source emission.
- Use `auditTime`: Ignores source values for duration milliseconds, then emits the most recent value from the source Observable, then repeats this process.
- Use `distinctUntilChanged`: with primitive data and consider use `isEqual` function from [lodash](https://lodash.com/docs/4.17.15#isEqual) for none-primitive data like array and object.

```typescript
import * as isEqual from 'lodash.isequal';
import { distinctUntilChanged } from 'rxjs/operators';

export class AComponent {
  constructor() {}

  get observable$() {
    return this.observable.pipe(distinctUntilChanged(isEqual));
  }
}
```

## Resources

- [Avoid an excessive DOM size](https://web.dev/dom-size/)
- [<ng-container> to the rescue](https://angular.io/guide/structural-directives#ng-container-to-the-rescue)
- [RxJS Patterns: Efficiency and Performance](https://blog.bitsrc.io/rxjs-patterns-efficiency-and-performance-10bbf272c3fc)
- [Angular Performance Checklist](https://github.com/mgechev/angular-performance-checklist)
- [These 5 articles will make you an Angular Change Detection expert](https://indepth.dev/these-5-articles-will-make-you-an-angular-change-detection-expert/#avoiding-common-confusions--2/)
- [3 Ways to Render Large Lists in Angular](https://dev.to/angular/3-ways-to-render-large-lists-in-angular-10nl)
- [Increasing Performance - more than a pipe dream - Tanner Edwards - YouTube](https://www.youtube.com/watch?v=I6ZvpdRM1eQ)
- [Help Angular to make your application faster](https://indepth.dev/help-angular-to-make-your-application-faster/)
- [Let Angular Manage Your RxJS Subscriptions Better](https://medium.com/better-programming/let-angular-manage-your-rxjs-subscriptions-better-9243073e94b0)