Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 74 ยท Quality and Performance

Performance Tuning

Speed up Angular apps by measuring first, then shrinking bundles, tracking lists, using signals and OnPush, virtual scrolling and the Angular DevTools profiler.

Performance work has one rule above all the others: measure before you change anything. Developers guess wrong about what is slow all the time. Angular gives you good defaults, and most apps need only a few well-aimed fixes: ship less JavaScript, do less work per update, and render fewer elements. This lesson shows how to find the real problem and a toolbox of fixes, each with a runnable stand-in you can experiment with.

It builds on change detection, control flow, signals, lazy routes and deferrable views.

The real Angular code, CLI output and tools are read-only: the site cannot run the Angular compiler, a bundler or Angular DevTools. The runnable examples are stand-ins that count work (function calls, rows touched, nodes rendered) instead of timing it, because counts are the same on every machine. They model the ideas; real numbers always come from your own profiler.

Two kinds of slow

Users complain about two different things, and they have different fixes.

flowchart TD
  S["The app feels slow"] --> Q{"When?"}
  Q -->|"Before anything appears"| L["Load performance<br/>LCP, bundle size, network"]
  Q -->|"After it appears, when using it"| R["Runtime performance<br/>INP, change detection, big lists"]
  Q -->|"Things jump around"| J["Layout stability<br/>CLS, image sizes, late content"]
  L --> LF["Smaller bundles, lazy routes, @defer,<br/>SSR, optimized images"]
  R --> RF["Signals and OnPush, track, computed,<br/>virtual scroll, less work per event"]
  J --> JF["Width and height on images,<br/>sized placeholders"]

Decide which kind of slowness you have before you pick a fix.

The standard yardsticks are the Core Web Vitals, measured on real users:

Metric Measures "Good" threshold
LCP (Largest Contentful Paint) When the main content appears 2.5 seconds or less
INP (Interaction to Next Paint) How quickly the page responds after a click, tap or key press 200 ms or less
CLS (Cumulative Layout Shift) How much the layout jumps 0.1 or less

Lighthouse (in Chrome DevTools) gives a lab measurement of these; tools such as the Chrome UX Report and PageSpeed Insights show real-user data. Always test a production build (ng build), because the development build is much slower and does extra checks.

Shrinking the bundle

The browser has to download, parse and run your JavaScript. For load performance, less is better.

See what you ship. ng build prints the size of each output file. To see what is inside, build with a stats file and open it in an analyzer, or use a source-map tool:

Terminal
ng build --stats-json
# open dist/<app>/stats.json in the esbuild bundle analyzer (a web page)

ng build --source-map
npx source-map-explorer dist/my-app/browser/*.js

Both draw a treemap where each rectangle is a library or file, sized by bytes. It is common to find one surprise: a whole utility library imported for one function, a date library with every locale, or a charting library in the first load.

Set budgets. Budgets turn bundle size into a check that fails the build when it grows too much. They live in angular.json, and new projects get sensible defaults:

JSON
"budgets": [
  { "type": "initial", "maximumWarning": "500kB", "maximumError": "1MB" },
  { "type": "anyComponentStyle", "maximumWarning": "4kB", "maximumError": "8kB" }
]

initial is the JavaScript and CSS needed for the first load. Tighten the numbers once your app is stable, so a pull request that adds 300 kB is noticed in review instead of in production.

Fixes that usually pay off:

  • Lazy-load routes (loadComponent, loadChildren) so users download a page's code when they visit it.
  • Use @defer for heavy widgets below the fold.
  • Import only what you use (import { debounce } from 'lodash-es', not the whole library), and prefer small libraries or native APIs such as Intl and structuredClone.
  • Keep third-party scripts out of the critical path.
  • Serve compressed files (gzip or Brotli) and cache hashed files for a long time; the CLI adds content hashes to file names.

Do less work per update

After the first load, performance is about how much work Angular does each time something changes.

Always use track in loops

@for requires a track expression for a reason. It tells Angular how to recognize "the same row" between updates. A stable key (an id) lets Angular keep existing DOM nodes and just move them; a poor key forces it to destroy and rebuild rows.

HTML
@for (item of items(); track item.id) {
  <app-row [item]="item" />
}

Prefer a unique, stable property such as id. track $index is acceptable for lists that never reorder or insert. track item (object identity) is a trap if the data is replaced with fresh objects from every server response, since every row then looks new.

Do not call expensive methods in templates

A template expression like {{ visibleProducts() }} that is a method runs every time change detection checks that component. In a default (zone-based) app, that is after every click, timer or response anywhere. Expensive work there repeats needlessly. Use a computed signal, which recalculates only when its inputs change, or a pure pipe:

TypeScript
readonly category = signal('books');
readonly visibleProducts = computed(() =>
  this.products()
    .filter((p) => p.category === this.category())
    .sort((a, b) => a.price - b.price),
);

Reading visibleProducts() ten times costs one calculation. A pure pipe behaves the same way for a given input value: Angular re-runs it only when its input reference changes. (Impure pipes run on every check; reserve them for rare cases.)

Signals, OnPush and zoneless

By default, Angular checks the whole component tree after any asynchronous event. OnPush components are skipped unless an input changes, an event comes from inside them, or something marks them dirty. Signals do this automatically: a component that reads a signal in its template is marked for refresh when that signal changes, and in a zoneless app (provideZonelessChangeDetection()) Angular schedules updates from signal changes and similar notifications instead of polling after every event. For new code: use changeDetection: ChangeDetectionStrategy.OnPush, keep state in signals, and treat objects as immutable (replace, don't mutate).

Keep high-frequency events cheap

scroll, mousemove and input can fire dozens of times per second. In a zone-based app each one can trigger change detection, so wrap such listeners in NgZone.runOutsideAngular and only re-enter when state really changes, or debounce the work with RxJS' debounceTime (see interop). Never do heavy computation directly in an event handler; that is what ruins INP.

Render fewer elements

If a page needs 10,000 rows, the problem is not how fast Angular updates them but that the browser has to lay out and paint 10,000 elements. Virtual scrolling renders only the rows near the viewport and fakes the rest of the scroll height. The CDK provides it:

TypeScript
import { Component } from '@angular/core';
import { ScrollingModule } from '@angular/cdk/scrolling';

@Component({
  selector: 'app-big-list',
  imports: [ScrollingModule],
  template: `
    <cdk-virtual-scroll-viewport itemSize="48" style="height: 480px">
      <div *cdkVirtualFor="let row of rows" class="row">{{ row }}</div>
    </cdk-virtual-scroll-viewport>
  `,
})
export class BigListComponent {
  rows = Array.from({ length: 100_000 }, (_, i) => `Row ${i}`);
}

The catch: rows need a known (fixed) height for the simple strategy, and search-in-page and anchor links to off-screen rows don't work. For lists of a few hundred rows, pagination or plain @for is simpler and good enough.

Measure with the tools

  • Angular DevTools (a browser extension) has a Profiler tab. Record while you use the page, and it shows each change detection cycle, how long it took, and which components were checked. A component that runs on every cycle with a long bar is your suspect, and the component tree shows its OnPush status.
  • Chrome DevTools, Performance panel: record an interaction and look at the long tasks (over 50 ms) in the flame chart. This is how you find where INP time goes, whether in your code or in a library.
  • Lighthouse and PageSpeed Insights: load metrics and a list of concrete suggestions.
  • performance.mark() and performance.measure() in your own code time specific steps, and they show up in the Performance panel.

Change one thing, measure again, and keep it only if the number improves.

A runnable stand-in: do the work once

This stand-in simulates change detection: a "render" pass runs repeatedly, and each pass needs the filtered, sorted product list. The naive version recomputes in every pass (a method in the template); the memoized version recomputes only when the signal it depends on changes (a computed). It counts the calls, which is the same on every machine, and also checks which approach was faster.

TypeScript Stand-in: method call versus computed memoization

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The method version does the expensive filter and sort once per read, the memoized one only when category actually changed (the first read and the read after the change). Real change detection is smarter than this model, but the lesson stands: work that is repeated unchanged is waste, and computed removes it without any cache code of your own.

A runnable stand-in: why track matters

Here a list of 1,000 rows is updated in four ways, and the stand-in counts how many rows would be created, destroyed or rewritten with three different track choices.

TypeScript Stand-in: counting DOM work for different track keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Track by id does almost nothing in every case: it recognizes each row, even after a reorder or a refetch. Track by $index rewrites the content of nearly every row when you prepend or remove (every position now holds different data). Track by object identity is fine until you refetch, when it destroys and recreates every row because the objects are new. This is why a stable, unique id is the best key.

A runnable stand-in: virtual scrolling

The core of virtual scrolling is arithmetic: from the scroll position, the item height and the viewport height, work out which rows to render and how much padding to put above and below.

TypeScript Stand-in: which rows does a virtual scroller render?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

At any position only about fifteen rows exist in the DOM, however long the list is. The scroll bar still reflects the full height, because the scroller adds a spacer of totalHeight and positions the rendered rows with offsetTop.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What should you do before optimizing an Angular app?

    Guessing leads to wasted effort. Measure first, change one thing, measure again, and keep only changes that help.
  2. 2. Why is track item.id better than track $index for a list that can be reordered or prepended to?

    With a stable id, Angular reuses and moves existing nodes. With the index, each position holds different data after an insert, so most rows are rewritten.
  3. 3. A template calls {{ sortedProducts() }}, a method that sorts 20,000 items. What is the best fix?

    A method runs on each check of the component. A computed signal caches its result until a signal it reads changes.
  4. 4. What does an "initial" budget in angular.json check?

    The initial budget limits the JavaScript and CSS that load at the start, and warns or fails the build when it grows past the thresholds.
  5. 5. When is virtual scrolling the right tool?

    Virtual scrolling renders only the rows near the viewport. It helps most for thousands of rows and works best with fixed row heights.

Summary

  • Measure first, on a production build: Lighthouse, the Chrome Performance panel and the Angular DevTools profiler; watch the Core Web Vitals LCP, INP and CLS.
  • Shrink the bundle with lazy routes, @defer, narrow imports, a bundle analyzer (--stats-json, source-map-explorer) and budgets in angular.json.
  • Always give @for a stable, unique track such as id; avoid track item with refetched data.
  • Replace template method calls with computed signals or pure pipes; use OnPush, signals and zoneless change detection to do less work per update.
  • Keep high-frequency handlers cheap, and use virtual scrolling for very long lists.
  • Angular code and tools are read-only; the call counts, row counts and window calculations are stand-ins.

Next: Security and Accessibility