Sub topic 10
Labeling your own code with User Timing
This chapter assumes you can record a trace in the Performance panel and read the flame chart. It also assumes you know basic TypeScript and Angular components. A trace of an Angular app shows many frames from the framework, from Zone.js, and from minified bundles. Your own code is hard to find among them. User Timing lets you put named labels into the trace so you can see exactly where your work starts and ends.
What User Timing is
User Timing is a browser API on the performance object. It has two main calls:
performance.mark(name)records a named point in time.performance.measure(name, startMark, endMark)records a named span between two marks.
Chrome DevTools reads these entries and draws them in the Timings track of a Performance panel recording. A measure appears as a labeled bar. A mark appears as a thin vertical line with a label. Because the entries sit on the same time axis as the flame chart, you can look straight down from a bar to see which functions ran during it.
The API does not change what your code does. It only adds entries to the browser's performance timeline. The cost of one call is small, but it is not zero, so use it on code you are investigating and not on every function.
A first example
The first example wraps a filtering method in a mark and a measure.
filterItems(term: string) {
performance.mark('filter-start');
const result = this.items.filter(i => i.name.includes(term));
performance.measure('filter', 'filter-start');
return result;
}The call performance.mark('filter-start') records the start. The call performance.measure('filter', 'filter-start') creates a span called filter. When you pass only a start mark, the span ends at the moment measure is called. If you leave out both marks, the span starts at the page's time origin, which is rarely what you want.
To use it:
- Run a production-like build, as described in the earlier chapter on production builds.
- Start a recording in the Performance panel.
- Type in the search box that calls
filterItems. - Stop the recording and open the Timings track.
- Find the bar named
filter. Its width is the time spent in the method.
If the bar is a few tenths of a millisecond wide, the filter is not your problem. If it is wide, you have confirmed a cost that you can then reduce and measure again.
Why this helps in an Angular trace
In a production build, function names are often shortened, and many frames belong to Angular and Zone.js. A method name such as filterItems may show up as a short, meaningless identifier. Source maps help, but a named bar in the Timings track is clearer and does not depend on them.
A Timings bar also answers a question the flame chart cannot answer directly: how long did this logical step take, including everything it called? The flame chart shows call stacks. A measure shows your own definition of a step, which may span several calls.
Measuring across several steps
A measure can span code that runs in different places, as long as the marks use the same names. Here is a service that loads and then prepares data.
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ReportService {
prepare(rows: { value: number }[]) {
performance.mark('prepare-start');
performance.mark('sort-start');
const sorted = [...rows].sort((a, b) => a.value - b.value);
performance.measure('sort', 'sort-start');
performance.mark('sum-start');
const total = sorted.reduce((sum, r) => sum + r.value, 0);
performance.measure('sum', 'sum-start');
performance.measure('prepare', 'prepare-start');
return { sorted, total };
}
}In the trace, prepare is one wide bar, and sort and sum appear as shorter bars that sit inside it. This shows which part of prepare takes the time without opening the flame chart first.
Passing options and details
performance.measure also accepts an options object. You can set start and end explicitly, and you can attach a detail value that DevTools can show.
const start = performance.now();
// ... work ...
performance.measure('render-batch', {
start,
end: performance.now(),
detail: { rows: 500 },
});Use detail to record the size of the input, such as the number of rows. A trace that shows a 40 ms bar is more useful when it also shows it handled 500 rows.
Marks and the Angular lifecycle
You can place marks in lifecycle hooks to see when Angular reaches a point. This helps when you want to know how long a component takes from creation to its first render.
import { AfterViewInit, Component, OnInit } from '@angular/core';
@Component({
selector: 'app-report',
template: `<p>Report</p>`,
})
export class ReportComponent implements OnInit, AfterViewInit {
ngOnInit() {
performance.mark('report-init');
}
ngAfterViewInit() {
performance.measure('report-first-render', 'report-init');
}
}The span covers the time from ngOnInit to ngAfterViewInit. It includes the first template render and the work of child components. It does not include the browser painting the result, because painting happens after your code returns. Treat it as a measure of the JavaScript side only.
Common mistakes
- Reusing a mark name that was never created.
performance.measurethrows aSyntaxErrorif the start mark does not exist. Check the spelling, and make sure the mark call runs before the measure call. - Overlapping names in loops. If a method runs many times, each call adds an entry with the same name. The trace shows many bars, which is fine, but reading entries by name later returns all of them. Use unique names or clear old entries when you read them programmatically.
- Measuring too much. A measure around a whole event handler tells you the handler is slow, but not why. Add smaller measures inside it, then narrow down.
- Leaving instrumentation in production code. Marks add entries to memory. Remove them after the investigation, or guard them so they are not in release builds.
- Expecting change detection to be inside the bar. Angular often runs change detection after your handler returns. A measure that ends when your method returns will not include that work. Look for the change detection frames after the bar in the flame chart.
Reading entries in code
You can also read the entries back, which is useful for quick checks in the Console.
const entries = performance.getEntriesByName('filter', 'measure');
const last = entries[entries.length - 1];
console.log(`filter took ${last.duration.toFixed(2)} ms`);Each entry has a duration in milliseconds. This approach is good for a quick number. For a repeatable comparison, record several runs and compare them, as the chapter on verifying an optimization describes.
Choosing where to place measures
Place a measure where the answer will change a decision. Good places include:
- Methods called from templates, because they run on every change detection pass.
- Event handlers that users report as slow.
- Data transformation steps, such as sorting, filtering, or mapping large arrays.
- The span between a user action and the point where your code has finished updating state.
| Question | Where to measure |
|---|---|
| Is my filter slow? | Around the filter call |
| Does this component render slowly? | From `ngOnInit` to `ngAfterViewInit` |
| Is a template method expensive? | Inside the method, on every call |
| Which step of a pipeline dominates? | One measure per step, plus one around the whole |
Exercise
You add performance.mark('a') at the start of a method and performance.measure('m', 'a') at the end. In the trace, the Timings bar is 3 ms wide, but the user still sees a delay of about 40 ms after the click. Give two reasons the bar might be much shorter than the delay, and say where in the trace you would look next.
Show answer
First, Angular may run change detection after the method returns, so that work falls outside the measure. Second, the browser's style, layout, and paint steps run after your JavaScript finishes, and they are not part of the measure. Look at the main-thread flame chart to the right of the bar for change detection frames and for Recalculate Style, Layout, and Paint entries.
Exercise
A call to performance.measure('total', 'total-start') throws a SyntaxError. What is the most likely cause, and how do you fix it?
Show answer
The mark named 'total-start' does not exist at the time measure runs, usually because of a typo or because the mark call is on a code path that did not run. Make sure performance.mark('total-start') runs first and that both names match exactly.