Angular course · Module 12: Security and Performance

Profiling and Diagnostics

2 min read ·
In this lesson5

Angular DevTools

Angular DevTools is an inspector for your application:

  1. Component Explorer - component tree
  2. Profiler - change detection performance analysis
  3. Injection Graph - dependency injection map
# Install the extension
# Chrome Web Store: Angular DevTools

Performance Profiling

// Enable profiling in development
import { ApplicationConfig } from '@angular/core';

export const appConfig: ApplicationConfig = {
  providers: [
    // In development we can enable detailed logging
  ]
};

// Manual measurements
@Component({...})
export class ProfiledComponent {
  loadData(): void {
    console.time('loadData');

    // Operations...

    console.timeEnd('loadData');
  }
}

Bundle Size Optimization

# Bundle analysis
ng build --stats-json
npx webpack-bundle-analyzer dist/browser/stats.json

# Source map explorer
npx source-map-explorer dist/browser/*.js

Tree Shaking

// BAD - import entire library
import * as lodash from 'lodash';

// GOOD - import only needed functions
import { debounce } from 'lodash-es';

// BEST - use native methods or write your own
const debounce = (fn: Function, ms: number) => {
  let timeoutId: ReturnType<typeof setTimeout>;
  return (...args: any[]) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn(...args), ms);
  };
};

trackBy for @for

@Component({
  template: `
    @for (samurai of samuraiList(); track samurai.id) {
      <app-samurai-card [samurai]="samurai" />
    }
  `
})
export class ListComponent {
  // track samurai.id prevents re-rendering
  // the entire list when only one element changes
}

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. How do you reduce the bundle size in Angular?

  2. 2. What is the Profiler tab in Angular DevTools used for?

Hands-on tasks in the game

  • Vertical ordering

    Order the lines that measure the time of an operation using console.time (top to bottom):

  • Code editor

    Complete the template with deferred loading of a heavy component.

  • Horizontal ordering

    Arrange a tree-shaking-friendly import (only the needed function, from the left):

  • Click in order

    Build the @for loop header with a track function by id (click in order):

  1. QuestionBundle Optimization
  2. QuestionProfiler in Angular DevTools
  3. Put in orderMeasuring time in code
  4. Coding taskPractice: @defer
  5. Put in orderTree-shaking-friendly import
  6. Click in orderTrack in the @for loop

Useful articles