Sub topic 8
Finding Expensive Code with the CPU Profiler
Assume you can write basic Dart, build simple Flutter widgets, and run an app on an emulator or device. You should also know how build methods and asynchronous Dart code work.
The CPU Profiler helps you find Dart code that uses too much processor time. It records samples of the call stack while your app runs. A call stack is the chain of functions that led to the code currently executing. If the same function appears in many samples, it probably consumes a large part of the available CPU time.
CPU profiling is useful when an app feels slow because it performs too much computation. It is less useful when the app waits for a server, a file, or a timer. Waiting is usually an input/output problem rather than a CPU problem.
Use profile mode first
Debug mode adds checks and other overhead. Those changes can make code appear slower than it is in a real application. Release mode is realistic, but it removes debugging features that help you investigate the problem.
Profile mode is the usual choice for performance investigation. It keeps profiling and DevTools support while producing measurements closer to a release build.
# Run the app in profile mode on a connected device
flutter run --profile
# Start DevTools on its own, then connect using the VM service URI printed by flutter run
dart devtoolsUse a physical device when possible. An emulator can have different processor and rendering performance from the devices used by your users.
Record and read a CPU profile
Start the app in profile mode, reproduce the slow action, and open the CPU Profiler in DevTools.
- Select the isolate that contains your app code.
- Start recording.
- Perform only the action you want to study.
- Stop recording.
- Inspect the functions with the largest CPU time.
An isolate is Dart's independent unit of execution. Most Flutter apps have one main isolate, but an app can also use isolates for background work.
The profiler may show a call tree, a bottom-up view, or a flame chart, depending on the DevTools version. These views answer slightly different questions:
| View | Question it answers |
|---|---|
| Call tree | Which path through my program used the time? |
| Bottom-up | Which function itself, or its callees, used the time? |
| Flame chart | How did calls expand during the recording? |
Focus on repeated application code rather than framework methods alone. A framework method may appear near the top because your code called it many times.
Add a useful timing label
Sampling tells you where the CPU spent time, but a named timeline event can make a known operation easier to recognize. Timeline.timeSync measures synchronous work and adds a named event to the timeline.
import 'dart:developer';
int sumOfSquares(List<int> values) {
return Timeline.timeSync('sumOfSquares', () {
var total = 0;
for (final v in values) {
total += v * v;
}
return total;
});
}Keep the measured section small. If one label surrounds network access, animations, and parsing, the result will not tell you which operation is expensive. Add labels around separate operations instead.
Interpret the result carefully
A large inclusive time means a function and the functions it calls used substantial CPU time. A large exclusive time means the function's own body used substantial time. Both matter.
Common causes include:
- Repeating a costly loop during every widget rebuild.
- Sorting or filtering a large collection on the main isolate.
- Parsing a large response synchronously.
- Performing unnecessary JSON conversion.
- Rebuilding more widgets than the changed state requires.
- Calling expensive work from an animation callback.
A CPU profile does not prove that a function causes visible frame drops. Compare the recording with the Performance view. A function may use CPU time during a screen transition without exceeding the frame budget. Conversely, a short burst of work on the main isolate can make one frame miss its deadline.
A repeatable investigation
Do not optimize only because a function appears in the profile. First confirm that the function belongs to the slow path. Then make one focused change and repeat the same recording. Also check that the result is still correct and that memory use has not increased.
Exercise
Why should you avoid using a debug-mode CPU profile to decide whether an optimization is needed?
Show answer
Debug mode adds runtime checks and other overhead, so its timings may not represent the performance of a profile or release build.