Sub topic 11
Finding Expensive Template Expressions
What this chapter assumes
You can record a trace in the Performance panel and read a flame chart. You know that Zone.js triggers change detection after events, timers, and network responses. You have the Angular DevTools extension installed. This chapter covers how to find the template code that makes each change detection pass slow. The next chapter covers how to fix it with OnPush and signals.
Why template expressions cost so much
Angular evaluates every binding in a template on each change detection pass. A binding such as {{ total() }} or [class.active]="isActive(row)" calls your function every time, because Angular cannot know whether the result changed without calling it. A pass runs after every click, keystroke, timer tick, and HTTP response that Zone.js reports.
A cheap method called once is not a problem. A moderately expensive method called once per row, on every pass, is a problem. If 500 rows each call a method that takes 0.05 ms, every pass costs 25 ms. That is more than a whole 16 ms frame at 60 fps, and it recurs on every pass.
The cost has three factors:
- How long one evaluation takes.
- How many times the template evaluates it per pass, which is once per binding instance, including each row of a loop.
- How many passes run, which depends on how many events fire.
Profiling means measuring all three.
Spotting them in the flame chart
Record while you repeat the slow action, for example typing in a search box. In the Main track, look for tasks longer than 50 ms. Zoom in on one and read down the stack from the top.
In a production build, the frames you care about are the generated template functions. They carry names like OrderListComponent_Template, or OrderListComponent_For_3_Template for an @for block. Under them you see calls to your own methods, and under those, any library calls such as Array.prototype.reduce, sort, JSON.stringify, or Intl.NumberFormat. Source maps, from the earlier chapter on production builds, let DevTools show your original method names.
Look for these patterns:
- Wide frames directly under a template function. A method you wrote takes the time.
- Many narrow, identical frames side by side. A cheap method runs once per row. Select a region and read the Bottom-Up tab. The method's total self time and call count are listed there.
- The same task repeated for every event. For example, one pass for every
inputevent while the user types.
The Bottom-Up tab is the quickest way to rank costs. Sort by Self Time, and expand the top entry to see which template function calls it.
Confirming with Angular DevTools
The flame chart shows time but not which component owns it. Open the Angular tab in DevTools, go to Profiler, and press Record. Perform the same action, then stop. Each bar is one change detection pass, and the bar's height shows how long it took. Select a bar to see the component tree for that pass, with the time each component spent.
Look for a component that is slow in every pass, or that appears in passes that have nothing to do with it. A component that shows up in every pass despite unchanged inputs is a candidate for OnPush, covered in the next chapter.
A worked example
This component has three typical problems. It recalculates a total in a method, it formats a value with a method per row, and it runs a sort inside a getter.
import { Component } from '@angular/core';
interface Order {
id: number;
name: string;
price: number;
qty: number;
}
@Component({
selector: 'app-order-list',
template: `
<input placeholder="Filter" (input)="term = $any($event.target).value" />
<p>Grand total: {{ grandTotal() }}</p>
@for (o of sortedOrders; track o.id) {
<p>{{ o.name }}: {{ lineLabel(o) }}</p>
}
`,
})
export class OrderListComponent {
term = '';
orders: Order[] = Array.from({ length: 2000 }, (_, i) => ({
id: i,
name: `Item ${i}`,
price: (i % 50) + 1,
qty: (i % 7) + 1,
}));
get sortedOrders(): Order[] {
console.count('sortedOrders');
return [...this.orders]
.filter(o => o.name.includes(this.term))
.sort((a, b) => a.name.localeCompare(b.name));
}
grandTotal(): number {
console.count('grandTotal');
return this.orders.reduce((sum, o) => sum + o.price * o.qty, 0);
}
lineLabel(o: Order): string {
console.count('lineLabel');
const total = o.price * o.qty;
return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(total);
}
}A trace of typing into the input shows a long task per keystroke. In the flame chart, OrderListComponent_Template contains one wide get sortedOrders frame with localeCompare beneath it. It also contains a long run of narrow lineLabel frames, each with NumberFormat below it. grandTotal is a medium frame with reduce beneath it.
The console.count calls give a second view. After one keystroke the console may show grandTotal: 2, sortedOrders: 2, and lineLabel: 4000 or more. The @for loop evaluates lineLabel once per row, so it runs thousands of times per pass.
Common culprits
| Pattern in template | Why it is costly | What the trace shows | Column |
|---|---|---|---|
| `{{ compute(x) }}` with a loop inside | Re-runs the loop every pass | One wide frame under the template function | |
| `*ngFor="let r of getRows()"` or `@for (r of getRows(); ...)` | Builds a new array every pass and defeats list reuse | Wide frame plus DOM work from re-created rows | |
| Getter that sorts or filters | Allocates and sorts on every read | `sort` or `filter` under the getter | |
| Per-row `Intl` or `Date` formatting | Constructing `Intl.NumberFormat` is slow | Many narrow frames, each containing `NumberFormat` | |
| `{{ obj \ | json }}` on large objects | Serializes the whole object each pass | `JSON.stringify` under the pipe |
| Impure pipe on a big list | Runs every pass regardless of inputs | Pipe `transform` frames in every pass |
Pure pipes are not in this table because Angular only re-runs them when their input reference changes.
Isolating a suspect
When the flame chart is crowded, make the expression show itself. Wrap the suspect in the User Timing marks you saw in the earlier chapter, then check the Timings track. A mark and measure around grandTotal() gives a labelled bar on every call. You can then read the number of bars and their widths directly.
You can also temporarily replace the call to test your hypothesis. Bind to a constant in place of grandTotal() and record the same action again. If the long task shrinks sharply, that expression was responsible. This is a quick experiment and is not a fix.
Gotchas
- Chasing the wrong cost. A method that runs 2000 times at 0.001 ms each is cheaper than one that runs once at 5 ms. Rank by total time in Bottom-Up, not by how often a name appears.
- Profiling in dev mode. Dev-mode checks add work and inflate counts. Confirm findings in a production build.
- Fast machines hide the problem. Apply the CPU throttling you set up earlier. A 0.3 ms cost on your laptop can be 1.5 ms on a mid-range phone at 4x slowdown.
- Inlined or minified names. If frames show names like
tore, source maps are missing or not loaded. Fix that before reading the trace. - Costs outside the template. A long task under
ApplicationRef.tickthat never enters your own methods may come from many components being checked. That is an OnPush question, not a template one. - Side effects in expressions. Do not add
console.countpermanently. Logging in a template call is itself slow and should be removed after the investigation.
Choosing the fix
Matching the pattern to a fix keeps the next chapter's work focused:
- Work that depends only on inputs: move it to a
computedsignal or a pure pipe so it re-runs only when those inputs change. - Work that is repeated per row: precompute the value once when the data arrives, and store it on the row. Create
Intl.NumberFormatonce, not per call. - A component that is checked on every pass without changes: use OnPush.
- A list that changes in small ways: use
trackwith a stable id.
Exercise
A trace of a keystroke in the search box shows a 90 ms task. Inside it, OrderListComponent_For_3_Template contains 2000 narrow lineLabel frames of about 0.04 ms each, and a single get sortedOrders frame of 6 ms. Which expression should you look at first, and why?
Show answer
Start with lineLabel. Its frames add up to roughly 2000 × 0.04 ms = 80 ms, which accounts for almost all of the 90 ms task. The 6 ms sort is the larger single frame but contributes far less in total. Confirm by sorting the Bottom-Up tab by Self Time, and then move the formatting out of the per-row call, for example by creating the Intl.NumberFormat once and precomputing labels.
Exercise
You add console.count('grandTotal') and see 2 calls in a dev build after one click. Does grandTotal run twice in production?
Show answer
No. In production it runs once per change detection pass. Development mode runs an extra checking pass, which doubles the count. Verify with a production build or a performance.mark around the call.