Sub topic 2
Measure before you optimize
This chapter shows how to find out which rebuilds cost you frame time, so you can tell them apart from rebuilds that are harmless. It assumes you can write a StatefulWidget, you know what setState does, and you can run an app on a device or emulator. You should also know that build can run many times for the same widget.
Why a rebuild count is not a cost
A widget that rebuilds often is not necessarily a problem. Flutter is designed to call build freely. Most build methods only create small, short-lived widget objects, and Flutter then compares them with the previous ones. A Text that rebuilds 60 times a second costs almost nothing.
Three numbers decide whether a rebuild matters:
- How many times it happens. A rebuild on every animation frame costs far more than one on every tap.
- How much work each
builddoes. Sorting a list, parsing JSON, or building a thousand children insidebuildis expensive. Returning aPaddingis not. - How large the rebuilt subtree is. A
setStateat the top of a screen with hundreds of descendants re-runsbuildfor every descendant that is not skipped.
You can see the first and third numbers with logging. The second needs a profiler. This chapter covers both and tells you which one to reach for.
Debug mode versus profile mode
Flutter has three build modes, and they behave very differently.
| Mode | Command | Use it for |
|---|---|---|
| Debug | `flutter run` | Logging rebuilds, hot reload, asserts |
| Profile | `flutter run --profile` | Measuring frame times on a real device |
| Release | `flutter run --release` | Final checks, no profiling hooks |
Debug mode runs your Dart code with extra checks and without full optimization, so frame times in debug mode are not representative. Use debug mode to count and locate rebuilds. Use profile mode on a physical device to decide whether a rebuild is slow. Emulators and simulators have different CPU and GPU characteristics, so do not draw conclusions about frame time from them.
Tool 1: log every rebuild
The framework has a debug flag that prints each element as it is built. Set it before runApp:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
if (kDebugMode) {
// Prints "Building X" the first time and "Rebuilding X" afterwards.
debugPrintRebuildDirtyWidgets = true;
}
runApp(const MaterialApp(home: CounterDemo()));
}
/// Logs a line each time its build method runs.
class BuildProbe extends StatelessWidget {
const BuildProbe({super.key, required this.label, required this.child});
final String label;
final Widget child;
@override
Widget build(BuildContext context) {
debugPrint('probe build: $label');
return child;
}
}
class CounterDemo extends StatefulWidget {
const CounterDemo({super.key});
@override
State<CounterDemo> createState() => _CounterDemoState();
}
class _CounterDemoState extends State<CounterDemo> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// A new instance on every build, so the probe rebuilds.
BuildProbe(label: 'plain header', child: const Text('Header')),
// The same instance on every build, so the probe is skipped.
const BuildProbe(label: 'const header', child: Text('Header')),
Text('Count: $_count'),
ElevatedButton(
onPressed: () => setState(() => _count++),
child: const Text('Add'),
),
],
),
);
}
}Run it with flutter run, wait for the first frame, and clear the console. Then tap the button once. You should see probe build: plain header and no line for the const header. The framework lines also show Rebuilding entries for the Text that displays the count and for the widgets above it that the framework refreshes. That output tells you which widgets ran build for that tap.
This also demonstrates a rule you will use in the next chapters. When a parent rebuilds, a child is skipped only if the framework receives the identical widget instance. A const expression gives you that. A new object that merely looks the same does not.
Reading the log
The output is a list of widget names in build order. When you read it, ask:
- Do widgets appear that have nothing to do with the state you changed? Those rebuilt because an ancestor rebuilt or because they depend on something that changed.
- Does the same widget appear in every frame while nothing is happening? Something is notifying continuously, such as an animation or a listener that fires on a timer.
- Is the list long for a single tap? The
setStateis probably too high in the tree.
The log has limits. It prints names, not durations, and a screen with a long list produces a lot of output. It can only show you where rebuilds happen. It cannot tell you whether they are expensive.
Tool 2: rebuild counts in the inspector
The Flutter Inspector, in DevTools and in the Flutter plugins for supported IDEs, can show how many times each widget in your own code has rebuilt. Turn on the rebuild count option in the inspector or the IDE's Flutter Performance panel, interact with the app, and look at the counters. The counts reset when you reset them in the tool.
This is the quickest way to find a widget with an unexpectedly high count. A button label that shows 200 rebuilds after you scroll a list is a clear signal. The availability and layout of this feature depend on your IDE and plugin version, so if you cannot find it, use the logging flag above. Counts still only measure frequency, not cost.
Tool 3: the DevTools Performance page
To measure cost, run in profile mode on a physical device and connect DevTools:
flutter run --profileOpen DevTools from the URL the command prints, or from your IDE, and go to the Performance page. Interact with the slow screen and look at the frame chart. Each bar is one frame, split into two parts:
- UI thread. This is where your Dart code runs, including
build, layout, and the creation of the paint commands. - Raster thread. This is where the engine turns those commands into pixels on the GPU.
A frame has a time budget. At 60 Hz it is about 16.6 ms, and at 120 Hz about 8.3 ms. A frame bar that goes over the budget is a janky frame. DevTools colors the bars so those frames stand out.
The thread that exceeds the budget tells you where to look:
- UI thread long. Too much work in
build, layout, or other Dart code. Rebuild reduction is relevant here. - Raster thread long. Expensive painting, such as large
saveLayeroperations, shadows, or clipping. Fewer rebuilds usually will not fix this. The last part of this tutorial covers whenRepaintBoundaryhelps. - Both long. Fix the UI thread first. It often causes the raster work as well.
Seeing which widgets cost time
Select a slow frame and open its timeline events. By default the events show the engine's phases but not individual widgets. DevTools has tracing options in the Performance page's enhance tracing settings, including one that adds an event for each widget built (called "Track widget builds"). With it on, the events for a slow frame list the widgets whose build ran, nested by parent, with durations.
The same behavior is available in code through a debug flag, if you want it on from startup:
import 'package:flutter/widgets.dart';
void main() {
// Adds a timeline event for each widget build in the next run.
debugProfileBuildsEnabled = true;
runApp(const MyApp());
}Tracing adds overhead of its own, so frame times with it enabled are larger than normal. Use it to find which widget is expensive, then turn it off and measure the real frame times again.
A decision flow
Common mistakes when measuring
- Measuring in debug mode. Timings are inflated and uneven. Count rebuilds in debug mode, but time them in profile mode.
- Measuring on an emulator. Use a real device, ideally a mid-range one rather than your fastest phone.
- Optimizing the first frame. The first build of a screen is always larger than later ones. Look at the frames produced by your interaction, such as a scroll or a tap.
- Changing several things at once. If you move state and add
constin the same edit, you will not know which change helped. Change one thing, then measure again. - Trusting one run. Frame times vary. Repeat the same interaction a few times and compare similar frames.
- Forgetting to remove the flags. Guard
debugPrintRebuildDirtyWidgetswithkDebugMode, and removedebugProfileBuildsEnabledbefore you commit. The probes in your ownbuildmethods should not ship either.
What to record
For each change, write down the interaction, the device, the mode, and the numbers before and after. For example: "Scroll the feed for 5 seconds on device X in profile mode. Before: 14 janky frames, the worst UI time 31 ms. After: 2 janky frames, the worst UI time 12 ms." Without a recorded baseline, you cannot show that a change worked, and you cannot notice when a later change undoes it. The final chapter turns this record into a repeatable audit workflow.
Exercise
A list screen feels slow when you scroll. In profile mode on a physical device, DevTools shows each janky frame with a short UI thread time of about 4 ms and a raster thread time of about 28 ms. Your rebuild log shows many Rebuilding lines. Should you start by reducing rebuilds? Explain, and name the next thing to check.
Show answer
No. The frame is over budget because of the raster thread, not the UI thread, and build work runs on the UI thread. The many rebuild lines show frequency, not cost, and at 4 ms of UI time they are cheap. Reducing rebuilds would barely change the frame time. Next, investigate painting work such as shadows, clipping, or layers that are repainted on every frame, and check whether a RepaintBoundary helps.