Sub topic 1
Measure first: why profile before changing code
Most Angular performance advice sounds convincing: "use OnPush", "avoid function calls in templates", "add trackBy". Each tip helps in some apps and does nothing in others. This chapter explains why you should measure before you change any code, and it sets up the working method for the rest of the tutorial.
Prerequisites
This chapter assumes you already have the following:
- Basic Angular knowledge: components, templates, and services.
- Familiarity with TypeScript and the browser event loop, including the idea that one main thread runs your JavaScript, style, layout, and paint work.
- The ability to run an Angular app locally with the Angular CLI.
- Basic Chrome DevTools use, such as opening panels and the Console.
You don't need to know the Performance panel yet. Later chapters cover it.
Why guessing fails
Developers usually guess wrong about where time goes. Three reasons are common:
- The slow part is rarely the part that looks slow. A template that calls a method may look wasteful, yet the method may take 0.01 ms. A third-party chart library that you never read may take 400 ms.
- Fixes have a cost. Switching a component tree to
OnPushcan introduce stale views and extra code. If the change gains nothing measurable, you took on that risk for no benefit. - Your machine is not your user's machine. A fast laptop hides problems that appear on a mid-range phone with a CPU several times slower.
Measuring first replaces opinion with evidence. It also tells you when to stop: once the problem is gone, you have a number that shows it.
What "slow" means in numbers
"The app feels slow" is not something you can test. Turn it into a quantity tied to what the browser does. The thresholds below are the ones the later chapters use.
| Quantity | Threshold | Meaning |
|---|---|---|
| Frame budget | about 16.7 ms at 60 Hz | Work on the main thread for one frame must finish within this time to keep animation smooth. |
| Long task | over 50 ms | A single main-thread task this long can delay input handling. Chrome reports these as long tasks. |
| Interaction to Next Paint (INP) | 200 ms or less is rated good | The time from a user's input until the next frame is painted. |
A good performance goal names one of these, one scenario, and one target. For example: "Typing in the search box should produce no task longer than 50 ms, on a 4x CPU slowdown."
The measurement loop
The method has the same shape every time. You pick a scenario, record a baseline, form a hypothesis from the evidence, change one thing, and record again.
Three rules keep the loop honest:
- Same scenario, same steps. Click the same button, type the same text, scroll the same distance.
- Same conditions. Use the same build, browser profile, throttling settings, and data set.
- One change at a time. If you change three things and the result improves, you don't know which one helped. One of them may even have hurt.
Noise is part of the data
A single run is a weak measurement. Timings vary because of garbage collection, other tabs, background processes, and browser caches. Repeat the scenario and compare typical values, not best cases.
The helper below runs a function many times and reports the median. The median is less sensitive to one unusually slow run than the average is. It discards one warm-up run, because the first call often includes one-time costs such as JIT compilation.
export function benchmark(label: string, work: () => void, runs = 20): number {
work(); // warm-up run, not recorded
const times: number[] = [];
for (let i = 0; i < runs; i++) {
const start = performance.now();
work();
times.push(performance.now() - start);
}
times.sort((a, b) => a - b);
const median = times[Math.floor(times.length / 2)];
const min = times[0];
const max = times[times.length - 1];
console.log(
`${label}: median ${median.toFixed(2)} ms, min ${min.toFixed(2)} ms, max ${max.toFixed(2)} ms over ${runs} runs`
);
return median;
}
const items = Array.from({ length: 50_000 }, (_, i) => ({ name: `item-${i}` }));
benchmark('filter 50k items', () => {
items.filter(i => i.name.includes('99'));
});If min and max are far apart, the result is noisy, and a small difference between two such results means nothing. Fix the noise first by closing other tabs, disabling extensions, or running more times.
This helper only times JavaScript you call directly. It does not capture style calculation, layout, or paint that happen after your code returns. The Performance panel, which you will use from the next chapters, shows all of that work.
Common traps
These mistakes make a measurement look useful when it isn't.
- Profiling a development build.
ng serveuses the development configuration. Angular adds extra checks in that mode, and the code is not optimized the way a production bundle is. Time spent in dev-only checks can look like a real problem. The next chapter covers how to profile a production-like build and keep source maps so you can still read function names. - Measuring only on a fast machine. If the target users have slower devices, test with CPU throttling. A later chapter covers it.
- Optimizing the first thing you see. A function that appears in a trace may account for 2% of the time. Fix the largest cost first, because that is where a fix pays off.
- Treating one trace as proof. Record at least three times. If the shape of the trace changes between recordings, find out why before you act.
- Comparing runs with different data. A list of 200 rows and a list of 2,000 rows behave differently. Keep the data set fixed between baseline and comparison.
- Keeping a change that made no difference. If the numbers did not move beyond the noise you saw, revert the change. Unneeded optimizations make code harder to read.
A worked example of the mindset
Suppose a product list feels laggy while the user types in a filter box. The tempting reaction is to add OnPush to every component. Using the loop instead:
- Scenario and target. Type "shoe" into the filter box. No task should exceed 50 ms at a 4x CPU slowdown.
- Baseline. Three recordings show one task of about 180 ms per keystroke.
- Biggest cost. The trace shows most of that time is inside one component's change detection, not in the filter function itself.
- One change. Apply a targeted fix to that component only.
- Compare. Record three more times under the same conditions. If the typical task falls below 50 ms, the target is met and you stop.
Had you started by rewriting the filter function, you would have optimized a part that took a few milliseconds. The trace is what points you to the right place. Later chapters teach you to read it.
What comes next
The remaining chapters follow the loop. You will set up a production-like build, record and read traces, connect what you see to Angular change detection and Zone.js, apply fixes, and verify each one against the baseline.
Exercise
A teammate says, "I added OnPush to the whole dashboard and it feels faster." You have no earlier recordings. Name two reasons this claim is not yet reliable, and say what you would do to test it.
Show answer
First, there is no baseline, so "feels faster" cannot be compared with anything, and perception is easily influenced by expectation or by differences in the machine or data. Second, the claim covers many components at once, so even if the page is faster you don't know which change helped or whether some changes did nothing. To test it, check out the code from before the change, define a scenario and a target (for example, a long task limit of 50 ms at a 4x CPU slowdown), and record at least three baseline traces. Then record three traces of the OnPush version using the same build type, data, and throttling. Compare typical values and keep the change only if the difference is larger than the run-to-run noise.