Performance
suggest changeDart is fast: in a release build your code is compiled ahead-of-time (AOT) to native machine code, and during development a JIT compiler optimizes hot code while it runs. Most slow Dart programs are slow not because of the language but because of an algorithm or an access pattern: a linear search inside a loop, a lazy iterable evaluated many times, sequential await of independent requests, or CPU-heavy work that blocks the event loop.
This article shows how to measure correctly and covers the changes that make the biggest difference in practice.
All timings below were measured with Dart 3.13 on a Windows laptop. Absolute numbers will differ on your machine; what matters is the ratio between the variants.
Measure first
Never optimize by guessing. The basic tool is Stopwatch from dart:core:
int sumTo(int n) {
var s = 0;
for (var i = 0; i < n; i++) {
s += i % 7;
}
return s;
}
void main() {
for (var run = 1; run <= 5; run++) {
final sw = Stopwatch()..start();
final r = sumTo(10000000);
sw.stop();
print('run $run: ${sw.elapsedMicroseconds} us (result $r)');
}
}
Running it with dart run:
run 1: 50044 us (result 29999994)
run 2: 39669 us (result 29999994)
run 3: 27678 us (result 29999994)
run 4: 24613 us (result 29999994)
run 5: 26915 us (result 29999994)
The first run is twice as slow as the later ones. Under dart run the code starts unoptimized; the JIT compiler notices that sumTo is hot and replaces it with optimized machine code. A benchmark that measures one call measures the compiler, not your code.
The same program compiled with dart compile exe is fast from the first call, because the code was optimized before the program started:
$ dart compile exe bin/p1.dart -o p1.exe
$ ./p1.exe
run 1: 18801 us (result 29999994)
run 2: 24726 us (result 29999994)
run 3: 25692 us (result 29999994)
run 4: 35776 us (result 29999994)
run 5: 31442 us (result 29999994)
Notice the noise: runs 4 and 5 are slower only because other programs were busy on the machine. A few rules follow:
- warm up the code before measuring, and repeat the measurement many times,
- report the best or the median time, not a single number,
- measure the way you ship: if you deploy an AOT executable (see Compiling to executables) or a Flutter release build, benchmark that, not
dart run.
A tiny benchmark helper
The examples in the rest of this article use this helper, saved as bin/bench.dart:
/// Runs [body] for [warmup] iterations, then measures [runs] batches
/// and reports the fastest and median time per call.
void bench(String name, void Function() body,
{int warmup = 200, int runs = 15, int callsPerRun = 100}) {
for (var i = 0; i < warmup; i++) {
body();
}
final times = <double>[];
final sw = Stopwatch();
for (var r = 0; r < runs; r++) {
sw
..reset()
..start();
for (var i = 0; i < callsPerRun; i++) {
body();
}
sw.stop();
times.add(sw.elapsedMicroseconds / callsPerRun);
}
times.sort();
final best = times.first.toStringAsFixed(1);
final median = times[times.length ~/ 2].toStringAsFixed(1);
print('${name.padRight(24)} best $best us median $median us');
}
Make sure the benchmarked function produces a result that is used (printed, compared, stored). An optimizing compiler is allowed to delete work whose result nobody reads, and then you measure an empty loop.
package:benchmark_harness
For benchmarks you keep in a repository, use the official benchmark_harness package (dart pub add dev:benchmark_harness). You subclass BenchmarkBase and put the measured code in run():
import 'package:benchmark_harness/benchmark_harness.dart';
class ListSumBenchmark extends BenchmarkBase {
ListSumBenchmark() : super('ListSum');
late List<int> data;
int result = 0;
@override
void setup() => data = List.generate(100000, (i) => i);
@override
void run() {
var s = 0;
for (final x in data) {
s += x;
}
result = s;
}
}
void main() {
final b = ListSumBenchmark();
b.report();
print('result: ${b.result}');
}
Output:
ListSum(RunTime): 2569.633 us.
result: 4999950000
setup() and teardown() are not measured. report() warms up for at least 100 ms and then measures for at least 2 seconds. Be aware that the reported time is for exercise(), which by default calls run() 10 times, so a single run() here takes about 257 us. For async code there is AsyncBenchmarkBase.
Pick the right data structure
The biggest wins come from algorithmic complexity, not micro-tuning. List.contains scans the whole list (O(n)); Set.contains and Map lookups are hash-based (O(1) on average):
import 'bench.dart';
final ids = List.generate(5000, (i) => i * 3);
final idSet = ids.toSet();
final queries = List.generate(5000, (i) => i * 2);
int countList() {
var n = 0;
for (final q in queries) {
if (ids.contains(q)) n++;
}
return n;
}
int countSet() {
var n = 0;
for (final q in queries) {
if (idSet.contains(q)) n++;
}
return n;
}
void main() {
print('${countList()} == ${countSet()}');
bench('List.contains', countList, warmup: 5, runs: 5, callsPerRun: 5);
bench('Set.contains', countSet);
}
Output:
1667 == 1667
List.contains best 14051.2 us median 14776.4 us
Set.contains best 25.2 us median 26.3 us
That is 500x faster for 5000 elements, and the gap grows with the size of the data. Whenever you see contains, indexOf or firstWhere inside a loop, consider building a Set or a Map keyed by id once, before the loop. Keys used in sets and maps must have a good hashCode and == (see Equality and comparison).
Build strings with StringBuffer
Strings are immutable. s += x in a loop allocates a new, longer string on every iteration and copies the old contents into it, which makes the loop O(n²):
import 'bench.dart';
final words = List.generate(10000, (i) => 'word$i');
String concat() {
var s = '';
for (final w in words) {
s += '$w ';
}
return s;
}
String buffer() {
final sb = StringBuffer();
for (final w in words) {
sb
..write(w)
..write(' ');
}
return sb.toString();
}
String joined() => words.join(' ');
void main() {
assert(concat().trim() == buffer().trim());
bench('String +=', concat, warmup: 5, runs: 5, callsPerRun: 2);
bench('StringBuffer', buffer);
bench('join', joined);
}
Output:
String += best 31941.0 us median 43498.5 us
StringBuffer best 247.5 us median 294.2 us
join best 259.4 us median 269.3 us
StringBuffer collects the parts and builds the final string once; join does the same internally. For a handful of pieces, interpolation ('$a-$b') is perfectly fine and the most readable. See Building from parts for more.
Watch out for lazy iterables
where, map, skip, take and friends return a lazy Iterable. Nothing is computed until you iterate it, and it is recomputed every time you iterate it:
var calls = 0;
bool isExpensiveMatch(int x) {
calls++;
return x % 3 == 0;
}
void main() {
final numbers = List.generate(1000, (i) => i);
final lazy = numbers.where(isExpensiveMatch);
print('count: ${lazy.length}');
print('first: ${lazy.first}');
print('sum: ${lazy.fold(0, (a, b) => a + b)}');
print('predicate calls (lazy): $calls');
calls = 0;
final eager = numbers.where(isExpensiveMatch).toList();
print('count: ${eager.length}');
print('first: ${eager.first}');
print('sum: ${eager.fold(0, (a, b) => a + b)}');
print('predicate calls (toList): $calls');
}
Output:
count: 334
first: 0
sum: 166833
predicate calls (lazy): 2001
count: 334
first: 0
sum: 166833
predicate calls (toList): 1000
length on a lazy where runs the predicate over all 1000 elements, first runs it again, and fold runs it a third time. If you use the result more than once, materialize it with toList() or toSet(). If you only iterate once, the lazy form is better because it avoids allocating an intermediate list.
Size lists up front and use typed data
A growable list that you fill with add has to grow its backing storage several times. When you know the length in advance, a fixed-length list is faster:
import 'bench.dart';
const n = 100000;
List<int> growable() {
final out = <int>[];
for (var i = 0; i < n; i++) {
out.add(i * i);
}
return out;
}
List<int> filled() {
final out = List<int>.filled(n, 0);
for (var i = 0; i < n; i++) {
out[i] = i * i;
}
return out;
}
List<int> generated() => List<int>.generate(n, (i) => i * i, growable: false);
List<int> mapped() => [for (var i = 0; i < n; i++) i * i];
void main() {
bench('add() to growable', growable);
bench('List.filled + index', filled);
bench('List.generate', generated);
bench('collection for', mapped);
}
Output (AOT executable):
add() to growable best 1506.8 us median 2034.6 us
List.filled + index best 494.0 us median 560.4 us
List.generate best 433.9 us median 563.2 us
collection for best 1079.8 us median 1617.8 us
For large arrays of numbers, dart:typed_data goes further. A List<double> stores a pointer to a separately allocated boxed double for each element. A Float64List stores raw 8-byte values next to each other, like a C array, which uses less memory and is friendlier to the CPU cache. The example also shows what happens when type information is lost with dynamic:
import 'dart:typed_data';
import 'bench.dart';
const n = 100000;
final listDouble = List<double>.generate(n, (i) => i * 0.5);
final typed = Float64List.fromList(listDouble);
final List<dynamic> dyn = List<dynamic>.of(listDouble);
double sumList(List<double> xs) {
var s = 0.0;
for (var i = 0; i < xs.length; i++) {
s += xs[i];
}
return s;
}
double sumTyped(Float64List xs) {
var s = 0.0;
for (var i = 0; i < xs.length; i++) {
s += xs[i];
}
return s;
}
double sumDynamic(List<dynamic> xs) {
dynamic s = 0.0;
for (var i = 0; i < xs.length; i++) {
s += xs[i];
}
return s;
}
void main() {
print('${sumList(listDouble)} ${sumTyped(typed)} ${sumDynamic(dyn)}');
bench('List<double>', () => sumList(listDouble));
bench('Float64List', () => sumTyped(typed));
bench('List<dynamic>', () => sumDynamic(dyn));
print('Float64List bytes: ${typed.lengthInBytes}');
}
With dart run (JIT):
2499975000.0 2499975000.0 2499975000.0
List<double> best 88.5 us median 103.5 us
Float64List best 68.3 us median 72.3 us
List<dynamic> best 85.4 us median 99.0 us
Float64List bytes: 800000
As an AOT executable:
2499975000.0 2499975000.0 2499975000.0
List<double> best 92.4 us median 117.1 us
Float64List best 79.3 us median 82.8 us
List<dynamic> best 433.4 us median 547.4 us
Float64List bytes: 800000
This is a good example of why you must measure the build you ship. The JIT observes that the dynamic values are always doubles and speculatively optimizes for that, so under dart run dynamic looks free. The AOT compiler cannot speculate; every + on dynamic becomes a dynamic method call with type checks, and the loop is 5x slower. Keep hot code statically typed: declare types, avoid dynamic, and convert JSON (Map<String, dynamic>) into typed classes at the boundary (see JSON).
Typed lists (Uint8List, Int32List, Float64List and so on) are also what dart:io uses for bytes, they can be sent between isolates cheaply, and they are the bridge to native code with dart:ffi.
Prefer plain string operations over regular expressions in hot loops
Regular expressions are powerful but have overhead. For simple checks, contains, startsWith and indexOf are much faster:
import 'bench.dart';
final lines = List.generate(2000, (i) => 'id=$i name=user$i email=u$i@example.com');
int countEmailsSlow() {
var n = 0;
for (final line in lines) {
// A new RegExp object is created for every line.
if (RegExp(r'email=\S+@\S+').hasMatch(line)) n++;
}
return n;
}
final _emailRe = RegExp(r'email=\S+@\S+');
int countEmailsFast() {
var n = 0;
for (final line in lines) {
if (_emailRe.hasMatch(line)) n++;
}
return n;
}
int countEmailsNoRegExp() {
var n = 0;
for (final line in lines) {
final i = line.indexOf('email=');
if (i >= 0 && line.indexOf('@', i) > 0) n++;
}
return n;
}
void main() {
print('${countEmailsSlow()} ${countEmailsFast()} ${countEmailsNoRegExp()}');
bench('RegExp in loop', countEmailsSlow, warmup: 20, callsPerRun: 10);
bench('RegExp hoisted', countEmailsFast);
bench('indexOf', countEmailsNoRegExp);
}
Output (AOT executable):
2000 2000 2000
RegExp in loop best 2914.4 us median 3491.6 us
RegExp hoisted best 3387.8 us median 4048.3 us
indexOf best 266.7 us median 326.0 us
Two lessons here. First, the indexOf version is more than 10x faster than either regular expression. Second, creating the RegExp inside the loop made no measurable difference: the Dart VM keeps a cache of recently compiled patterns, so the expensive compilation happens only once. That is exactly the kind of "obvious" optimization that measuring proves unnecessary. Storing the pattern in a top-level final is still good style, since it names the pattern and makes it reusable, but don't expect it to speed things up.
Async code: don't serialize independent work
await suspends the function until the future completes. Awaiting independent operations one after another adds up their latencies; starting them all first and then waiting for all of them overlaps them:
Future<String> fetch(String name, int ms) async {
await Future<void>.delayed(Duration(milliseconds: ms));
return name;
}
Future<void> main() async {
var sw = Stopwatch()..start();
final a = await fetch('user', 300);
final b = await fetch('orders', 300);
final c = await fetch('prices', 300);
print('sequential: [$a, $b, $c] in ${sw.elapsedMilliseconds} ms');
sw = Stopwatch()..start();
final (x, y, z) = await (
fetch('user', 300),
fetch('orders', 300),
fetch('prices', 300),
).wait;
print('concurrent: [$x, $y, $z] in ${sw.elapsedMilliseconds} ms');
}
Output:
sequential: [user, orders, prices] in 951 ms
concurrent: [user, orders, prices] in 309 ms
The .wait extension on a record of futures (Dart 3) keeps each result's type; for a list of futures of the same type use Future.wait or .wait on the list. This matters most for network and database calls (see Async and Await).
async has a cost in tight loops
Every call to an async function allocates a Future and every await goes through the event loop's microtask queue. That is negligible next to real I/O, but not for a function that returns an already-available value millions of times:
final cache = <int, int>{for (var i = 0; i < 100; i++) i: i * 2};
Future<int> lookupAsync(int k) async => cache[k]!;
int lookupSync(int k) => cache[k]!;
Future<void> main() async {
const n = 1000000;
var sw = Stopwatch()..start();
var s = 0;
for (var i = 0; i < n; i++) {
s += await lookupAsync(i % 100);
}
print('async: ${sw.elapsedMilliseconds} ms (sum $s)');
sw = Stopwatch()..start();
s = 0;
for (var i = 0; i < n; i++) {
s += lookupSync(i % 100);
}
print('sync: ${sw.elapsedMilliseconds} ms (sum $s)');
}
Output (AOT executable):
async: 197 ms (sum 99000000)
sync: 19 ms (sum 99000000)
Keep pure computation synchronous and make only the I/O boundary async. A cache in front of a slow async call can return a synchronous value on a hit, for example with FutureOr<T> or by checking the cache before calling the async function (see Caching).
Use isolates for CPU-bound work
A Dart isolate runs on one thread. Long computations block its event loop: a server stops answering requests and a Flutter app drops frames. Moving the work to other isolates keeps the main isolate responsive and, on a multi-core machine, runs the work in parallel:
import 'dart:isolate';
bool isPrime(int n) {
if (n < 2) return false;
for (var d = 2; d * d <= n; d++) {
if (n % d == 0) return false;
}
return true;
}
int countPrimes(int from, int to) {
var c = 0;
for (var i = from; i < to; i++) {
if (isPrime(i)) c++;
}
return c;
}
Future<void> main() async {
const limit = 6000000;
var sw = Stopwatch()..start();
final single = countPrimes(0, limit);
print('1 isolate: $single primes in ${sw.elapsedMilliseconds} ms');
sw = Stopwatch()..start();
const workers = 4;
const chunk = limit ~/ workers;
final parts = await Future.wait([
for (var w = 0; w < workers; w++)
Isolate.run(() => countPrimes(w * chunk, (w + 1) * chunk)),
]);
final total = parts.reduce((a, b) => a + b);
print('$workers isolates: $total primes in ${sw.elapsedMilliseconds} ms');
}
Output (AOT executable):
1 isolate: 412849 primes in 2707 ms
4 isolates: 412849 primes in 878 ms
The speedup is 3x rather than 4x because the chunks are uneven (testing large numbers takes longer) and spawning isolates and sending results back has a cost. Messages between isolates are copied, so send compact data (numbers, typed lists, TransferableTypedData) rather than huge object graphs. See Isolates for long-lived workers.
Profiling with DevTools
Benchmarks tell you how fast something is; a profiler tells you where the time goes. Run the program with the VM service enabled:
$ dart run --observe --pause-isolates-on-exit bin/p12.dart
The Dart VM service is listening on http://127.0.0.1:8181/tx3Kmp3QdTQ=/
The Dart DevTools debugger and profiler is available at: http://127.0.0.1:8181/tx3Kmp3QdTQ=/devtools/?uri=ws://127.0.0.1:8181/tx3Kmp3QdTQ=/ws
total: 19999900000
report length: 11780
vm-service: isolate(2770539346951307) 'main' has no debugger attached and is paused at exit. Connect to the Dart VM service at http://127.0.0.1:8181/tx3Kmp3QdTQ=/ to debug.
Open the DevTools URL in a browser. The CPU Profiler tab shows a sampled call tree and a flame chart: functions with the largest "self time" are where the CPU actually spends its cycles. The Memory tab shows allocations and lets you take heap snapshots (see Memory and garbage collection). --pause-isolates-on-exit keeps a short program alive so you can inspect it after it finishes; for a server, plain --observe is enough. In VS Code and IntelliJ you can open DevTools directly from a debug session (see Debugging).
To see your own operations in the Performance timeline, mark them with dart:developer:
import 'dart:developer';
int parseAll(List<String> rows) {
var total = 0;
for (final r in rows) {
total += int.parse(r.split(',')[1]);
}
return total;
}
void main() {
final rows = List.generate(200000, (i) => 'item$i,$i');
final total = Timeline.timeSync('parseAll', () => parseAll(rows));
print('total: $total');
final task = TimelineTask()..start('report');
final sb = StringBuffer();
for (var i = 0; i < 1000; i++) {
sb.writeln(rows[i]);
}
task.finish();
print('report length: ${sb.length}');
}
Timeline.timeSync records a synchronous span and returns the callback's result. TimelineTask can also span asynchronous work that starts in one function and finishes in another. The calls are almost free when no tool is recording, so they can stay in the code.
Remember that profiling under dart run profiles JIT-compiled code. To profile an AOT build, use dart compile exe, then run the executable under a native profiler (perf on Linux, Instruments on macOS, Visual Studio or Windows Performance Analyzer on Windows), or for Flutter run in profile mode with flutter run --profile.
Compiler hints
The VM supports a few @pragma annotations for code that profiling has shown to be hot:
@pragma('vm:prefer-inline')
double lerp(double a, double b, double t) => a + (b - a) * t;
@pragma('vm:never-inline')
void logSlowPath(String message) => print(message);
vm:prefer-inline asks the compiler to inline a small function at every call site; vm:never-inline keeps a rarely-taken path out of the hot function so the hot code stays small. The compiler already inlines small functions on its own, so use these only after a measurement shows they help.
Other things that help the compiler without any annotations:
finallocal variables and fields, andconstconstructors, so identical objects are created once at compile time (see Constants),final,sealedandbaseclass modifiers, which tell the compiler that there are no unknown subclasses,- avoiding
dynamicand unnecessaryascasts in hot code.
Checklist
- Measure the build you ship (AOT executable, Flutter profile or release mode), with warm-up and repetition.
- Profile with DevTools to find the actual hot spot before changing code.
- Fix the algorithm first:
SetandMapinstead of searching lists, no repeated work inside loops. - Build strings with
StringBufferorjoin, not+=in a loop. - Materialize lazy iterables you use more than once with
toList(). - Pre-size lists, and use
dart:typed_datafor large numeric arrays. - Keep hot code statically typed; avoid
dynamic. - Run independent I/O concurrently with
Future.waitor.wait; keep pure computation synchronous. - Move CPU-heavy work to isolates with
Isolate.run. - Re-measure after every change, and keep the change only if the numbers improved.