When you're making small improvements to your code, how do you know if they actually make things faster? It's hard to tell without measuring. That's where benchmarking comes in.
Small optimizations needs numbers to prove they work. And you can measure how long a part of your Flutter code takes to run right within your tests!
Why Measure Performance in Tests?
Adding performance checks to your tests helps you catch slowdowns early. If a code change makes something unexpectedly slow, your test will fail. This is much better than finding out later in production.
How to Benchmark
You can use the built-in Stopwatch
class in Dart to time how long a specific action or set of actions takes.
The Stopwatch
Think of Stopwatch
like a simple timer. You start it, let some code run, and then check how much time has passed.
Checking the Time
The Stopwatch
gives you the elapsed time in different units, like milliseconds or microseconds.
Here’s how you can use Stopwatch
inside a testWidgets
block to check the performance of tapping a button:
testWidgets('check huge function performance', (
WidgetTester tester,
) async {
final sw = Stopwatch()..start();
await tester.tap(find.byKey(const ValueKey('btn')));
await tester.pumpAndSettle(const Duration(milliseconds: 100));
expect(sw.elapsedMilliseconds, lessThan(500));
});
Breaking Down the Code
Starting the Clock
final sw = Stopwatch()..start();
creates a new stopwatch and starts it immediately.
Performing the Action
await tester.tap(find.byKey(const ValueKey('btn')));
simulates tapping a widget found by its key. This is the action you want to time.
await tester.pumpAndSettle(const Duration(milliseconds: 100));
waits for any animations or rebuilds triggered by the tap to finish. This is important to get a realistic measurement of the action's effect.
Checking the Result
expect(sw.elapsedMilliseconds, lessThan(500));
checks if the total time from starting the stopwatch until this line is less than 500 milliseconds. sw.elapsedMilliseconds
gives you the time passed since start()
was called.
By using Stopwatch
in your tests, you get clear numbers to see if your performance optimizations are working and to prevent regressions.