Sub topic 13
A repeatable measure, change, re-measure workflow
Earlier chapters showed you the individual tools: the frames chart, Frame Analysis, and Timeline Events. This chapter turns them into a routine you can repeat on any slow screen. The routine stops you from "fixing" things that weren't slow and from claiming wins you didn't measure.
This chapter assumes you can run an app in profile mode and open the DevTools Performance view. It also assumes you know the 16.7 ms budget for a 60 Hz display, and that you can tell UI-thread work from raster-thread work.
Why a workflow matters
Performance work fails in predictable ways:
- You change three things at once and can't tell which helped.
- You measure in debug mode, where timings are not representative.
- You compare runs where the app did different things, such as a cold start against a warm scroll.
- You trust how the app "feels" after a change, when a single run varies a lot.
The fix is to treat each change as a small experiment. Keep everything constant except one variable, record numbers before and after, and write down what you saw.
Step 1: Define a repeatable scenario
A scenario is a short, fixed sequence of user actions that triggers the jank. Examples are "cold start to the home screen", "scroll the product list from top to bottom once", or "tap the button five times".
Write the scenario down in a sentence. Anyone, including you next week, should be able to repeat it. Keep it short, ideally under 30 seconds, so you can run it many times.
Pick the device with care. Use the same physical device for every run, and prefer a mid-range or older phone over a flagship, because slow frames show up more clearly there. Close other apps and plug the device in, since battery saver modes can throttle the CPU. Emulators and desktop builds use different hardware, so their numbers don't predict phone performance.
Step 2: Capture a baseline in profile mode
Profile mode compiles ahead of time like release mode but keeps the hooks DevTools needs. Debug mode adds assertions and just-in-time compilation, which inflate timings.
flutter devices
flutter run --profile -d <device-id>Open DevTools from the link the command prints, then go to the Performance view. Before running the scenario, clear any data from earlier runs so the frames chart only shows this one. Then perform the scenario once and stop.
Record these for the baseline:
- The number of frames marked as janky (the red ones in the frames chart).
- The worst UI-thread time and the worst raster-thread time, in milliseconds.
- Which thread the slowest frames blame.
- One or two of the slowest frames, with their Frame Analysis hints and the top Timeline Events entries.
The first run after launch often includes one-time costs, such as loading assets and warming caches. Do one throwaway run, then count the next ones. If you can, repeat the scenario three times and look at the typical result rather than the best one.
A worked example
The following app has a single toggle you set at launch time with --dart-define. Both variants run in profile mode on the same device with the same scenario, so the only variable is the code path.
import 'dart:developer';
import 'dart:isolate';
import 'package:flutter/material.dart';
const bool useFix = bool.fromEnvironment('USE_FIX');
int slowSum() {
var total = 0;
for (var i = 0; i < 50000000; i++) {
total += i % 7;
}
return total;
}
void main() => runApp(const MaterialApp(home: CounterPage()));
class CounterPage extends StatefulWidget {
const CounterPage({super.key});
@override
State<CounterPage> createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
int _taps = 0;
// Lazy: the isolate only starts if the fixed path reads this field.
late final Future<int> _sumFuture = Isolate.run(slowSum);
Widget _buildResult() {
if (!useFix) {
// Baseline: expensive work on the UI thread, labelled for the trace.
final value = Timeline.timeSync('slow_sum', slowSum);
return Text('Result: $value');
}
return FutureBuilder<int>(
future: _sumFuture,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Text('Calculating...');
}
return Text('Result: ${snapshot.data}');
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const CircularProgressIndicator(),
const SizedBox(height: 24),
_buildResult(),
Text('Taps: $_taps'),
ElevatedButton(
onPressed: () => setState(() => _taps++),
child: const Text('Tap'),
),
],
),
),
);
}
}The spinner animates continuously, so any UI-thread stall is easy to see. The scenario is "launch, wait for the result, tap the button five times".
Run the baseline:
flutter run --profile -d <device-id>In the baseline, the first frame and every tap run slowSum inside build. In the frames chart you should see a long UI-thread bar on the first frame and on each tap. The Timeline Events tab shows a slow_sum event taking most of the frame. Because you labelled it with Timeline.timeSync, you don't have to guess which call it is.
Now run the variant with the one change, the isolate:
flutter run --profile -d <device-id> --dart-define=USE_FIX=trueRepeat the identical scenario. The taps should now produce short UI frames, and the heavy work happens off the UI thread.
Step 3: Form one hypothesis, make one change
A hypothesis names a cause and predicts a measurable effect. A good example is: "build calls slowSum, which blocks the UI thread. Moving it into an isolate should bring UI-thread time per frame under 16 ms."
This fits the evidence you collected. The frame is UI-bound, and the Timeline Events tab names the expensive call. A weak hypothesis would be "the app is slow, so I'll add const everywhere". It has no evidence behind it and predicts nothing you can check.
Make only one change per iteration. If you also add RepaintBoundary widgets and shrink images in the same pass, a better result tells you nothing about which change mattered. The next chapter-level habit, which is rolling back, also gets harder.
Use the evidence to pick which kind of change to try:
| Evidence in the trace | Likely direction |
|---|---|
| Long UI-thread bar, a single expensive function | Move work out of `build` or into an isolate |
| Long UI-thread bar, many widgets built | Narrow rebuilds so fewer widgets rebuild |
| Short UI bar, long raster bar | Reduce layers, clips, shadows, or image sizes |
| Raster spikes only on first appearance of an effect | Check shader compilation and Impeller |
Step 4: Re-measure the same scenario
Run the scenario again with the same device, mode, and steps. Clear the chart first. Then record the same numbers as in the baseline.
Keep a log. A table like this takes a minute to maintain and saves you from arguing with your memory. The numbers below are illustrative.
| Run | Change | Janky frames | Worst UI (ms) | Worst raster (ms) | Verdict |
|---|---|---|---|---|---|
| 1 | Baseline | 6 | 410 | 9 | UI-bound, `slow_sum` dominates |
| 2 | `Isolate.run`, started once | 0 | 11 | 9 | Fits the budget, keep |
Compare against the baseline, not against the previous result you remember. Treat small differences with suspicion. A change from 17 ms to 15 ms on a single run could be noise. A change from 410 ms to 11 ms is not.
Step 5: Decide, then repeat or stop
After re-measuring, you have three possible outcomes:
- Improved and within budget. Keep the change, record it, and stop. Further tuning has diminishing returns.
- Improved but still janky. Keep the change. The bottleneck may have moved, for example from UI to raster, so go back to Frame Analysis and form a new hypothesis.
- No improvement or worse. Revert the change. Your hypothesis was wrong, and that is useful information. Go back to the evidence.
Stopping matters as much as starting. The goal is frames that fit the budget on your target devices, not the lowest number you can reach.
Common mistakes
- Measuring in debug mode. Debug timings can be many times slower than profile timings, so you can end up optimising problems users never see.
- Leaving tracing flags on while comparing. The enhance-tracing options add timeline events and some overhead. Use the same tracing settings for the baseline and the re-measure, or keep them off for headline numbers and turn them on only to investigate.
- Changing the scenario between runs. Even scrolling at a different speed changes what the frames chart shows.
- Moving work to an isolate without checking the cost. Starting an isolate and copying large results back has a price. Confirm with a re-measure rather than assuming.
- Ignoring the first frame. Some jank is genuinely at startup. If that is what users hit, include startup in your scenario.
- Deleting the custom timeline events after the fix. Wrapping suspicious code in
Timeline.timeSyncis cheap in profile runs. Leave useful labels in place so the next regression is easier to find.
Making the workflow a habit
Three small practices make the loop dependable over time:
- Keep the measurement log in the pull request or issue that describes the fix. Reviewers can then see the before and after numbers.
- Save the scenario steps next to the code, for example in a short note in the repository. The next person can then repeat your run.
- Re-run the scenario when you upgrade Flutter, add a large dependency, or change a screen's layout. Regressions often arrive through unrelated changes.
Exercise
You run the baseline and see 6 janky frames with a worst UI time of 410 ms. You then move an expensive call into an isolate and also replace several images with smaller ones. The janky frames drop to 1. Why is this a weak experiment, and what would you do instead?
Show answer
Two changes were made at once, so you can't tell which one caused the improvement, and the remaining janky frame can't be attributed to either. Revert to the baseline and apply the changes one at a time, re-measuring the same scenario in profile mode on the same device after each. Record the numbers in a log, then check Frame Analysis and Timeline Events on the one remaining janky frame to form a new hypothesis.
Exercise
After a fix, the worst UI time falls from 410 ms to 11 ms, but the worst raster time rises from 9 ms to 22 ms. What do you conclude, and what is your next step?
Show answer
The UI-thread bottleneck is fixed, but the bottleneck has moved to the raster thread, and frames may still be janky. Keep the change, because it improved what it was meant to. Then form a new hypothesis from the raster-side evidence, for example expensive effects, clips, shadows, or large images. Make one change for that and re-measure the same scenario.