Benchmarks

suggest change

A benchmark answers one question: how long does this code take, and is variant B faster than variant A? It sounds simple, but a naive benchmark measures something else: the JIT compiler warming up, a loop the optimizer deleted, the clock's resolution, or another program using the CPU.

This article is about doing the measurement right:

For common optimizations (data structures, StringBuffer, typed data, isolates) see Performance. A benchmark tells you how fast something is; to find out where the time goes, use a profiler as described in Profiling.

The examples were run with Dart 3.13 and benchmark_harness 2.4.0 on a 24-core Windows machine that was busy with other work at the same time. That is deliberate: the noise you will see is typical of a developer laptop or a shared CI runner.

Use Stopwatch and time batches of calls

Stopwatch from dart:core uses a monotonic high-resolution clock. DateTime.now() is a wall clock. It changes in coarser steps, and it can jump when the system time is adjusted, so don't use it to time code.

Even with a good clock, one call to a fast function can't be measured meaningfully. Time many calls and divide:

int square(int x) => x * x;

void main() {
  final sw = Stopwatch();
  print('Stopwatch frequency: ${sw.frequency} ticks/s');

  // Timing a single tiny call: the result is mostly clock noise.
  var total = 0;
  final singles = <int>[];
  for (var i = 0; i < 8; i++) {
    sw
      ..reset()
      ..start();
    total += square(i);
    sw.stop();
    singles.add(sw.elapsedTicks);
  }
  print('single calls (ticks): $singles');

  // Timing a batch of calls and dividing gives a usable number.
  const n = 10000000;
  sw
    ..reset()
    ..start();
  for (var i = 0; i < n; i++) {
    total += square(i);
  }
  sw.stop();
  final ns = sw.elapsedTicks * 1e9 / sw.frequency / n;
  print('batched: ${ns.toStringAsFixed(2)} ns per call (total $total)');

  // DateTime.now() is a wall clock with coarser steps; it can also jump.
  var last = DateTime.now();
  final steps = <int>[];
  while (steps.length < 5) {
    final t = DateTime.now();
    if (t != last) {
      steps.add(t.difference(last).inMicroseconds);
      last = t;
    }
  }
  print('DateTime.now() steps (us): $steps');
}
Stopwatch frequency: 10000000 ticks/s
single calls (ticks): [947, 7, 2, 2, 2, 2, 2, 2]
batched: 3.12 ns per call (total 1291890006563071052)
DateTime.now() steps (us): [641, 1012, 755, 634, 516]

On Windows a tick is 100 ns, so a call that takes 3 ns can't be seen on its own. The first single call took almost 100 us because that code had never run before. When you time a batch, the per-call overhead of the clock disappears. elapsedMicroseconds and elapsed are fine for anything that takes longer than a few hundred microseconds; use elapsedTicks and frequency when you need more precision.

Don't let the compiler delete your benchmark

An optimizing compiler may remove code whose result is never used. It may also compute an expression with constant inputs once instead of on every iteration. A benchmark that falls into either trap measures an empty loop:

import 'dart:math';

double work(double x) => sqrt(x) * sin(x);

void main() {
  const n = 20000000;

  // 1. Result ignored: the compiler may remove the calls.
  var sw = Stopwatch()..start();
  for (var i = 0; i < n; i++) {
    work(i.toDouble());
  }
  print('result ignored:  ${sw.elapsedMilliseconds} ms');

  // 2. Result accumulated and printed: the work must happen.
  sw = Stopwatch()..start();
  var sum = 0.0;
  for (var i = 0; i < n; i++) {
    sum += work(i.toDouble());
  }
  print('result used:     ${sw.elapsedMilliseconds} ms (sum $sum)');

  // 3. Constant input: the compiler could compute it once.
  sw = Stopwatch()..start();
  var sum2 = 0.0;
  for (var i = 0; i < n; i++) {
    sum2 += work(42.0);
  }
  print('constant input:  ${sw.elapsedMilliseconds} ms (sum $sum2)');
}

With dart run (JIT):

result ignored:  21 ms
result used:     573 ms (sum -938.335479892834)
constant input:  366 ms (sum -118794769.94171204)

As an AOT executable (dart compile exe):

result ignored:  69 ms
result used:     669 ms (sum -938.335479892834)
constant input:  15 ms (sum -118794769.94171204)

The "result ignored" loop is 10-30x faster than the real work because the compiler dropped the calls. The AOT compiler also noticed that work(42.0) always returns the same value and hoisted it out of the loop. The JIT did not, so the same benchmark gives very different answers depending on how it runs.

Rules that prevent this:

A measuring helper with statistics

A single number hides how noisy a measurement is. The helper below does what a good harness does:

  1. Warm up for a fixed time, so the JIT optimizes the code before measurement.
  2. Calibrate: double the iteration count until one batch takes at least 10 ms, well above the clock's resolution.
  3. Take many samples of that batch size and report the median, the minimum, the 90th percentile and the relative standard deviation.

Save it as lib/measure.dart in a package called dartbench:

import 'dart:math';

/// Prevents the compiler from treating benchmark results as dead code.
Object? sink;

class Stats {
  final String name;
  final List<double> samples; // nanoseconds per operation, sorted
  Stats(this.name, List<double> s) : samples = [...s]..sort();

  double get min => samples.first;
  double get median => _percentile(50);
  double get p90 => _percentile(90);
  double get mean => samples.reduce((a, b) => a + b) / samples.length;
  double get stddev {
    final m = mean;
    final v = samples.map((x) => (x - m) * (x - m)).reduce((a, b) => a + b) /
        (samples.length - 1);
    return sqrt(v);
  }

  /// Relative standard deviation in percent.
  double get rsd => stddev / mean * 100;

  double _percentile(int p) {
    final i = (p / 100 * (samples.length - 1)).round();
    return samples[i];
  }

  @override
  String toString() => '${name.padRight(16)}'
      ' median ${_fmt(median)}  min ${_fmt(min)}'
      '  p90 ${_fmt(p90)}  ±${rsd.toStringAsFixed(1)}%';
}

String _fmt(double ns) {
  if (ns < 1e3) return '${ns.toStringAsFixed(1)} ns'.padLeft(10);
  if (ns < 1e6) return '${(ns / 1e3).toStringAsFixed(2)} us'.padLeft(10);
  return '${(ns / 1e6).toStringAsFixed(2)} ms'.padLeft(10);
}

/// Finds how many calls of [body] take at least [target].
int calibrate(Object? Function() body,
    {Duration target = const Duration(milliseconds: 10)}) {
  var iterations = 1;
  final sw = Stopwatch();
  while (true) {
    sw
      ..reset()
      ..start();
    for (var i = 0; i < iterations; i++) {
      sink = body();
    }
    sw.stop();
    if (sw.elapsed >= target) return iterations;
    iterations *= 2;
  }
}

/// Measures [body] and returns per-call timings for [samples] batches.
Stats measure(String name, Object? Function() body,
    {int samples = 30, Duration warmup = const Duration(milliseconds: 500)}) {
  // Warm-up: run until the JIT has had a chance to optimize [body].
  final w = Stopwatch()..start();
  while (w.elapsed < warmup) {
    sink = body();
  }
  final iterations = calibrate(body);
  final sw = Stopwatch();
  final result = <double>[];
  for (var s = 0; s < samples; s++) {
    sw
      ..reset()
      ..start();
    for (var i = 0; i < iterations; i++) {
      sink = body();
    }
    sw.stop();
    result.add(sw.elapsedTicks * 1e9 / sw.frequency / iterations);
  }
  return Stats(name, result);
}

Every result goes into the top-level sink, so the compiler has to compute it. Here are three ways to sum a list, plus a fourth that turned out to matter:

import 'package:dartbench/measure.dart';

final data = List.generate(1000, (i) => (i * 7919) % 1000);

int sumLoop() {
  var s = 0;
  for (var i = 0; i < data.length; i++) {
    s += data[i];
  }
  return s;
}

int sumLoopLocal() {
  final d = data;
  var s = 0;
  for (var i = 0; i < d.length; i++) {
    s += d[i];
  }
  return s;
}

int sumForIn() {
  var s = 0;
  for (final x in data) {
    s += x;
  }
  return s;
}

int sumFold() => data.fold(0, (a, b) => a + b);

void main() {
  print(measure('index loop', sumLoop));
  print(measure('index local', sumLoopLocal));
  print(measure('for-in', sumForIn));
  print(measure('fold', sumFold));
}

Compiled with dart compile exe and run twice:

index loop       median   855.8 ns  min   807.8 ns  p90   930.5 ns  ±13.6%
index local      median   495.3 ns  min   435.5 ns  p90   708.4 ns  ±21.8%
for-in           median   420.8 ns  min   408.9 ns  p90   439.4 ns  ±3.3%
fold             median    2.43 us  min    2.11 us  p90    2.92 us  ±14.1%
index loop       median   734.8 ns  min   720.8 ns  p90   746.0 ns  ±1.4%
index local      median   635.5 ns  min   484.5 ns  p90   795.0 ns  ±17.8%
for-in           median   466.1 ns  min   442.3 ns  p90   476.0 ns  ±2.4%
fold             median    2.14 us  min    2.03 us  p90    2.22 us  ±3.3%

How to read this:

That last result is a good reason to benchmark: the local-variable version looks identical, yet it is consistently faster.

Warm up, and measure the build you ship

Under dart run, code starts unoptimized and the JIT compiles hot functions while the program runs. The first iterations are slow, so the helper above warms up for half a second before it samples. An AOT executable from dart compile exe is optimized before it starts, but it can't speculate on the types it sees at runtime. The two often rank the same code differently. Performance shows a dynamic loop that looks free under JIT and is 5x slower under AOT.

Benchmark in the mode your users run:

You ship Benchmark with
CLI tool or server built with dart compile exe the AOT executable
Server run with dart run or as a kernel snapshot dart run, with warm-up
Flutter app flutter run --profile on a real device, never debug mode
Web app dart compile js -O2 (or wasm) in the target browser

Two more things:

Comparing two variants: run an A/A test first

The useful question is rarely "how fast is X". It is "is B faster than A, and by how much". Measure both alternately several times, so that slow periods on the machine affect both. Then look at the spread of the ratio, not just one number.

Before you trust a difference, compare a function with an identical copy of itself (an A/A test). Whatever ratio that produces is pure noise:

import 'package:dartbench/measure.dart';

final keys = List.generate(200, (i) => 'key$i');
final map = {for (final k in keys) k: k.length};

int lookupIndex() {
  var s = 0;
  for (final k in keys) {
    s += map[k]!;
  }
  return s;
}

int lookupIndexCopy() {
  var s = 0;
  for (final k in keys) {
    s += map[k]!;
  }
  return s;
}

int lookupPutIfAbsent() {
  var s = 0;
  for (final k in keys) {
    s += map.putIfAbsent(k, () => 0);
  }
  return s;
}

/// Runs [a] and [b] alternately for [rounds] and reports the ratio b/a.
void compare(String nameA, Object? Function() a, String nameB,
    Object? Function() b,
    {int rounds = 10}) {
  final ratios = <double>[];
  for (var r = 0; r < rounds; r++) {
    final ma = measure(nameA, a, samples: 10, warmup: Duration.zero);
    final mb = measure(nameB, b, samples: 10, warmup: Duration.zero);
    ratios.add(mb.median / ma.median);
  }
  ratios.sort();
  String f(double x) => x.toStringAsFixed(2);
  print('$nameB / $nameA: median ${f(ratios[rounds ~/ 2])}'
      '  range ${f(ratios.first)} .. ${f(ratios.last)}');
}

void main() {
  // Warm up everything once before the comparisons.
  for (final f in [lookupIndex, lookupIndexCopy, lookupPutIfAbsent]) {
    measure('warmup', f, samples: 1);
  }
  compare('map[k]', lookupIndex, 'map[k] (copy)', lookupIndexCopy);
  compare('map[k]', lookupIndex, 'putIfAbsent', lookupPutIfAbsent);
}

Two runs of the AOT executable:

map[k] (copy) / map[k]: median 1.10  range 0.69 .. 1.43
putIfAbsent / map[k]: median 2.08  range 1.25 .. 2.55
map[k] (copy) / map[k]: median 0.90  range 0.41 .. 1.49
putIfAbsent / map[k]: median 1.78  range 1.34 .. 2.66

Identical code measured anywhere from 0.41x to 1.49x "faster" in a single round. On this machine a 10% or 20% difference means nothing. The putIfAbsent ratio is different: its median is around 2x in both runs and no round came out below 1.25x. That difference is real: putIfAbsent is slower than [] for keys that are already present. To pin the exact factor down you would need a quieter machine.

Guidelines for comparisons:

package:benchmark_harness

For benchmarks that you keep in the repository, use the Dart team's benchmark_harness package:

$ dart pub add dev:benchmark_harness

By convention benchmarks live in a top-level benchmark/ directory of the package. You subclass BenchmarkBase, put the measured code in run(), and put preparation that should not be timed in setup() and teardown(). report() warms up for 100 ms and then measures for at least 2 seconds.

Be aware of a legacy quirk: the default exercise() calls run() 10 times and the reported score is the time for those 10 calls. Override exercise() to report the time for one call. Results go to a ScoreEmitter. The default prints them, and you can supply your own, for example to collect them as JSON:

import 'dart:convert';

import 'package:benchmark_harness/benchmark_harness.dart';

/// Collects scores in a map instead of printing them.
class MapEmitter implements ScoreEmitter {
  final results = <String, double>{};

  @override
  void emit(String testName, double value) => results[testName] = value;
}

String makeInput() => jsonEncode([
      for (var i = 0; i < 100; i++)
        {'id': i, 'name': 'user$i', 'tags': ['a', 'b'], 'active': i.isEven},
    ]);

class JsonDecodeBenchmark extends BenchmarkBase {
  JsonDecodeBenchmark(ScoreEmitter emitter)
      : super('JsonDecode', emitter: emitter);

  late String input;
  Object? result;

  @override
  void setup() => input = makeInput();

  @override
  void run() => result = jsonDecode(input);

  // Report the time of one run() instead of ten.
  @override
  void exercise() => run();
}

class JsonEncodeBenchmark extends BenchmarkBase {
  JsonEncodeBenchmark(ScoreEmitter emitter)
      : super('JsonEncode', emitter: emitter);

  late Object? data;
  String result = '';

  @override
  void setup() => data = jsonDecode(makeInput());

  @override
  void run() => result = jsonEncode(data);

  @override
  void exercise() => run();
}

void main() {
  final emitter = MapEmitter();
  JsonDecodeBenchmark(emitter).report();
  JsonEncodeBenchmark(emitter).report();
  for (final MapEntry(:key, :value) in emitter.results.entries) {
    print('${key.padRight(12)} ${value.toStringAsFixed(2)} us');
  }
  print(jsonEncode(emitter.results));
}
$ dart run benchmark/json_benchmark.dart
JsonDecode   78.31 us
JsonEncode   135.46 us
{"JsonDecode":78.3060074249072,"JsonEncode":135.45567555405557}

Storing the result in a field (result = ...) keeps the work from being optimized away. Without a custom emitter, the output looks like JsonDecode(RunTime): 78.306 us..

Running on several platforms with the bench command

The package includes a bench command that compiles and runs the same benchmark as an AOT executable, on the JIT, as JavaScript on Node.js, or as WebAssembly:

$ dart run benchmark_harness:bench --flavor aot --flavor jit --flavor js --target benchmark/json_benchmark.dart
AOT - COMPILE
...dart.exe compile exe benchmark/json_benchmark.dart -o ...\out.exe

AOT - RUN
JsonDecode   58.38 us
JsonEncode   135.71 us

JIT - RUN
JsonDecode   117.01 us
JsonEncode   91.53 us

JS - COMPILE
Compiled 10,747,093 input bytes (5,326,982 characters source) to 52,684 characters JavaScript in 0.46 seconds

JS - RUN
JsonDecode   46.21 us
JsonEncode   60.59 us

(Output shortened.) The rankings flip between platforms. Decoding was fastest on Node.js because dart2js uses the JavaScript engine's native JSON.parse. Encoding was faster on the JIT than in the AOT build. If your code runs on several platforms, benchmark each one. Without --target the command runs benchmark/benchmark.dart. In our test on Windows, the wasm flavor compiled but failed to start under Node.js because of a path issue, so run Wasm benchmarks in a browser instead.

Async benchmarks

AsyncBenchmarkBase has the same structure with Future-returning methods. Its exercise() calls run() once, so the score is per call. It suits I/O and anything that uses await:

import 'dart:io';

import 'package:benchmark_harness/benchmark_harness.dart';

class ReadFileBenchmark extends AsyncBenchmarkBase {
  ReadFileBenchmark(super.name, {required this.chunked});

  final bool chunked;
  late Directory dir;
  late File file;
  int bytes = 0;

  @override
  Future<void> setup() async {
    dir = await Directory.systemTemp.createTemp('bench');
    file = File('${dir.path}/data.bin');
    await file.writeAsBytes(List.filled(4 * 1024 * 1024, 7));
  }

  @override
  Future<void> teardown() => dir.delete(recursive: true);

  @override
  Future<void> run() async {
    if (chunked) {
      var n = 0;
      await for (final chunk in file.openRead()) {
        n += chunk.length;
      }
      bytes = n;
    } else {
      bytes = (await file.readAsBytes()).length;
    }
  }
}

Future<void> main() async {
  await ReadFileBenchmark('readAsBytes', chunked: false).report();
  await ReadFileBenchmark('openRead', chunked: true).report();
}
readAsBytes(RunTime): 7260.046931407942 us.
openRead(RunTime): 15707.0546875 us.

Reading a 4 MB file in one call is about twice as fast as streaming it in 64 KB chunks. Streaming is still the right choice for files that don't fit comfortably in memory. Note that I/O benchmarks mostly measure the OS file cache after the first iteration, not the disk.

Measuring memory

Time isn't the only cost. ProcessInfo from dart:io reports the resident set size (RSS) of the process: currentRss now and maxRss at its peak. RSS is coarse because it includes the VM itself and memory the garbage collector hasn't returned to the OS. It works well for comparing variants of a big data structure, each in a fresh process:

import 'dart:io';
import 'dart:typed_data';

class Point {
  final double x, y;
  Point(this.x, this.y);
}

String mb(int bytes) => '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';

void main(List<String> args) {
  const n = 2000000;
  final before = ProcessInfo.currentRss;
  final sw = Stopwatch()..start();

  Object data;
  if (args.first == 'objects') {
    data = List.generate(n, (i) => Point(i * 1.0, i * 2.0));
  } else {
    // x0, y0, x1, y1, ... packed into one typed array
    final xy = Float64List(n * 2);
    for (var i = 0; i < n; i++) {
      xy[2 * i] = i * 1.0;
      xy[2 * i + 1] = i * 2.0;
    }
    data = xy;
  }

  sw.stop();
  print('${args.first}: ${sw.elapsedMilliseconds} ms, '
      'RSS +${mb(ProcessInfo.currentRss - before)}, '
      'peak ${mb(ProcessInfo.maxRss)} (${data.runtimeType})');
}
$ dart compile exe bin/memory.dart -o mem.exe
$ ./mem.exe objects
objects: 76 ms, RSS +46.9 MB, peak 59.5 MB (List<Point>)
$ ./mem.exe typed
typed: 8 ms, RSS +30.5 MB, peak 43.1 MB (Float64List)

Two million points take about 50% more memory as objects than as raw doubles in a Float64List, and they take almost 10x longer to create, because every Point is a separate allocation the garbage collector has to track. For allocation counts per class and heap snapshots, use the DevTools memory view (see Memory and garbage collection).

Benchmarking whole programs and startup time

For command-line tools, startup time often matters more than peak throughput. Measure it from the outside by launching the process repeatedly. The first run is untimed so the OS file cache is warm for all variants:

import 'dart:io';

/// Runs a command [runs] times and reports wall-clock statistics.
Future<void> timeCommand(String label, String exe, List<String> args,
    {int runs = 10}) async {
  // One untimed run fills the OS file cache.
  await Process.run(exe, args);
  final times = <int>[];
  for (var i = 0; i < runs; i++) {
    final sw = Stopwatch()..start();
    final r = await Process.run(exe, args);
    sw.stop();
    if (r.exitCode != 0) throw Exception('$label failed: ${r.stderr}');
    times.add(sw.elapsedMilliseconds);
  }
  times.sort();
  print('${label.padRight(22)} min ${times.first} ms'
      '  median ${times[runs ~/ 2]} ms  max ${times.last} ms');
}

Future<void> main() async {
  await Process.run('dart', ['compile', 'exe', 'bin/hello.dart', '-o', 'hello.exe']);
  await Process.run('dart', ['compile', 'kernel', 'bin/hello.dart', '-o', 'hello.dill']);

  await timeCommand('dart bin/hello.dart', 'dart', ['bin/hello.dart']);
  await timeCommand('dart hello.dill', 'dart', ['hello.dill']);
  await timeCommand('hello.exe (AOT)', './hello.exe', []);
}

bin/hello.dart is just void main() => print('hello');:

dart bin/hello.dart    min 283 ms  median 328 ms  max 395 ms
dart hello.dill        min 86 ms  median 123 ms  max 160 ms
hello.exe (AOT)        min 30 ms  median 42 ms  max 60 ms

Running from source compiles the program on every start. A kernel snapshot skips parsing. An AOT executable starts about 8x faster than source. See Compiling to executables for the build options and Running OS commands for more on Process. A dedicated tool such as hyperfine does the same job with better statistics, if you have it installed.

Catching regressions in CI

A benchmark is most valuable when it runs regularly and alerts you when a change makes code slower. Save the JSON produced by the emitter above as a baseline, and compare each new run against it:

import 'dart:convert';
import 'dart:io';

/// Usage: dart run bin/check_regression.dart baseline.json current.json
void main(List<String> args) {
  Map<String, double> load(String path) =>
      (jsonDecode(File(path).readAsStringSync()) as Map<String, dynamic>)
          .map((k, v) => MapEntry(k, (v as num).toDouble()));

  final baseline = load(args[0]);
  final current = load(args[1]);
  const threshold = 0.20; // fail if more than 20% slower

  var failed = false;
  for (final MapEntry(key: name, value: now) in current.entries) {
    final before = baseline[name];
    if (before == null) {
      print('$name: new benchmark, ${now.toStringAsFixed(2)} us');
      continue;
    }
    final change = (now - before) / before;
    final pct = '${change >= 0 ? '+' : ''}${(change * 100).toStringAsFixed(1)}%';
    final status = change > threshold ? 'REGRESSION' : 'ok';
    print('${name.padRight(12)} ${before.toStringAsFixed(2)} -> '
        '${now.toStringAsFixed(2)} us  $pct  $status');
    if (change > threshold) failed = true;
  }
  exitCode = failed ? 1 : 0;
}

Here is the JSON benchmark compiled once and run twice, with no code change in between:

$ ./json_benchmark.exe | tail -1 > baseline.json
$ ./json_benchmark.exe | tail -1 > current.json
$ dart run bin/check_regression.dart baseline.json current.json
JsonDecode   76.60 -> 94.36 us  +23.2%  REGRESSION
JsonEncode   115.66 -> 109.77 us  -5.1%  ok

The same binary "regressed" by 23%. This is the central problem of performance testing on shared machines, and it is why the A/A test matters. To make a check like this reliable:

The non-zero exit code makes the CI step fail. See Testing in CI for wiring Dart tools into a pipeline.

Checklist

  1. Decide what you measure and in which mode: AOT, JIT, Flutter profile mode or the web, matching what you ship.
  2. Time with Stopwatch, never DateTime.now(), and time batches long enough (milliseconds, not nanoseconds).
  3. Use every result and generate inputs at runtime so the compiler can't delete or precompute the work.
  4. Warm up, take many samples, and compare medians; check the spread before trusting a number.
  5. Run an A/A test to learn your noise level, and interleave variants when comparing them.
  6. Use benchmark_harness for benchmarks you keep. Remember that BenchmarkBase reports 10 calls of run() unless you override exercise().
  7. Measure memory and startup time too, in fresh processes.
  8. Automate regression checks on quiet hardware, with thresholds above the measured noise.
  9. When a benchmark shows a problem, profile to find the cause, fix it (see Performance), and measure again.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents