Sub topic 17
Verifying an optimization with before-and-after traces
This chapter assumes you can record a trace in the Performance panel and read its flame chart. It also assumes you know what long tasks are and have used the Angular DevTools profiler. Here you will learn how to show that a change made the app faster, instead of assuming it did.
Why a single "it feels faster" is not evidence
Performance numbers vary from run to run. Garbage collection, background tabs, browser extensions, CPU temperature, and cache state all move the result. A change that saves 5 ms can vanish in that noise, and a change that saves nothing can look like a win after one lucky run.
Verification means holding everything constant except the change, measuring several times, and comparing the same metrics before and after.
Fix the conditions
Write down the conditions and keep them identical for both sides of the comparison.
- Use the same build type. Compare production-like builds, with source maps enabled so function names stay readable.
- Use the same browser profile. An Incognito window with extensions disabled removes most outside interference.
- Use the same throttling, for example 4x CPU slowdown. Throttling is applied by DevTools, so also write down the setting.
- Use the same data. A list of 50 rows and a list of 5,000 rows are different experiments.
- Use the same scenario, with the same steps in the same order.
- Close other heavy tabs and applications, and keep the laptop plugged in.
Define the scenario and the metric first
Choose the user action that was slow, such as typing in a filter box or opening a large table. Then choose a metric before you record anything. Picking the metric after you see the results invites choosing whichever number looks best.
| Metric | Where to read it | What it tells you |
|---|---|---|
| Duration of a User Timing measure | Timings track, or `performance.getEntriesByName` | Cost of one specific operation |
| Total scripting time in the range | Summary tab, Scripting row | Overall JavaScript cost of the scenario |
| Long task count and longest task | Main track, red-flagged tasks | Whether the main thread blocks long enough to hurt input |
| Change detection passes and duration | Angular DevTools profiler | How often and how expensively Angular checks views |
| Heap size after the scenario | Memory panel | Leaks, not speed |
Prefer a metric tied to your own code. The performance.mark and performance.measure pair from the earlier chapter works well here, because the measure has a fixed name and can be read the same way every time.
filterItems(term: string) {
performance.mark('filter-start');
const result = this.items.filter(i => i.name.includes(term));
performance.measure('filter', 'filter-start');
return result;
}Make the measurement repeatable
Repeat the scenario at least five times per side. Reload the page between runs so each starts from the same state, or use a fixed, scripted action that returns the app to its starting state.
You can collect durations without opening a trace each time. Paste this into the Console after running the scenario several times. It reads every filter measure and prints the median, which resists a single outlier better than the mean.
function summarize(name) {
const durations = performance
.getEntriesByName(name, 'measure')
.map(entry => entry.duration)
.sort((a, b) => a - b);
if (durations.length === 0) {
return { name, runs: 0 };
}
const mid = Math.floor(durations.length / 2);
const median =
durations.length % 2 === 1
? durations[mid]
: (durations[mid - 1] + durations[mid]) / 2;
return {
name,
runs: durations.length,
min: durations[0],
median,
max: durations[durations.length - 1],
};
}
console.table([summarize('filter')]);To count long tasks during a scenario, register an observer before you start and read it afterward.
const longTasks = [];
const observer = new PerformanceObserver(list => {
longTasks.push(...list.getEntries());
});
observer.observe({ type: 'longtask', buffered: true });
// Run the scenario, then:
observer.disconnect();
console.log({
count: longTasks.length,
longest: Math.max(0, ...longTasks.map(t => t.duration)),
});The observer reports tasks that take 50 ms or more. Use it only as a count. The trace stays the source of truth for what the task contained.
The before-and-after workflow
- Record the baseline and save each trace. In the Performance panel, use the download (Save profile) button to export a JSON file, and name it for what it is, such as
filter-baseline-run1.json. - Make exactly one change. If you change
OnPush,track, and a template expression together, you cannot say which one helped. - Rebuild with the same build command and reload.
- Record the same scenario under the same throttling.
- Compare the metrics you chose in advance.
You can reload a saved trace with the Load profile button, so you can compare it side by side with the new one at any time.
Compare traces in the panel
Open the baseline and the new trace in two windows. Select the same range in each, covering the same scenario steps, and compare the Summary tab. Then look at the Bottom-Up tab for the function you targeted. Its self time should fall if your change worked.
Also check that the shape of the flame chart changed in the way you predicted. If you added OnPush to stop a component from being checked, the refreshView calls for that component should be gone or rarer. If the total fell but those calls did not, something else changed the number, and you should find out what.
In Angular DevTools, record the profiler for the same interaction before and after. Compare how many change detection cycles ran and which components appear in them. A component that checked on every cycle before and checks only when its inputs change afterward is direct evidence.
Decide whether the difference is real
Compare ranges, not just medians. If the baseline ran from 38 to 52 ms and the new version ran from 36 to 49 ms, the ranges overlap almost fully and you have shown nothing. If the baseline ran from 38 to 52 ms and the new one from 9 to 14 ms, the ranges do not overlap and the change is clear.
Throttling helps here. A 4x CPU slowdown multiplies real differences, which lifts them above the noise, and it also better matches mid-range phones. A fast development machine can hide a problem that users on slower devices see.
Check what the optimization cost
A faster number is not enough on its own. Before you keep a change, confirm these points:
- The behavior is still correct.
OnPushand signals can leave a view stale if a value changes without notifying Angular, and a wrongtrackexpression can reuse the wrong DOM node. - Other scenarios did not slow down. Moving work out of change detection into a service or a larger bundle can shift cost elsewhere. Check load cost in the Network panel if you added code.
- Memory is stable. Listeners registered outside the zone are not cleaned up by Angular. Confirm in the Memory panel that heap size does not grow across repeated runs.
Common mistakes
- Changing several things at once, so the cause is unknown.
- Recording once and trusting the result.
- Recording the "after" with the DevTools window open differently, for example with the Console flooded with logs that were absent before.
- Leaving
performance.markcalls in a hot path forever. They are cheap but not free, so remove them or guard them once you are done. - Declaring success because the flame chart looks shorter, without checking a number.
Keep the evidence
Record what you did in the pull request or ticket: the scenario, throttling, build command, number of runs, and before and after medians with ranges. Attach the saved trace files if your team allows it. A later regression is much easier to spot when a baseline exists.
Exercise
You added OnPush to a table component and recorded one trace before and one after. The after trace shows 30 ms less scripting time. A colleague says this proves the change worked. What is missing, and what would you do?
Show answer
One run per side cannot show that the 30 ms is more than normal run-to-run noise. Record the scenario at least five times per side under the same build, throttling, and data. Compare the medians and ranges. Also confirm in the flame chart or Angular DevTools that the component's change detection calls dropped, and check that the view still updates correctly.
Exercise
After your change, the median of a 'filter' User Timing measure drops from 40 ms to 12 ms, but the page still feels slow while typing. Name one metric to check next and where to read it.
Show answer
Check long tasks in the main track of the Performance panel, or the count of change detection passes in the Angular DevTools profiler. The filter itself may be faster while other work, such as template re-rendering or checking the whole component tree on each keystroke, still blocks the main thread.