microbench

package version dart support likes pub points test

A zero-dependency microbenchmark harness for Dart.
Side-by-side tables · Significance tests · Regression checks · JIT / AOT / JS / WASM · Markdown · HTML · Text · JSON

Compare Dart implementations on the same inputs, see how their timings vary, and check for regressions across revisions. Run benchmarks as native executables, on the Dart VM, or as JavaScript and WebAssembly on Node.js.

📦 Install

Add microbench as a development dependency.

dart pub add dev:microbench

⚡ Quickstart

Save this comparison as benchmark/string_benchmark.dart. Each variant returns the string it builds so the harness can consume the result.

import 'package:microbench/microbench.dart';

void main() {
  group('Repeat one char, 1000 times', () {
    benchmark('+ operator', () {
      var s = '';
      for (var i = 0; i < 1000; i++) {
        s += 'x';
      }
      return s;
    });
    benchmark('StringBuffer', () {
      final sb = StringBuffer();
      for (var i = 0; i < 1000; i++) {
        sb.write('x');
      }
      return sb.toString();
    });
    benchmark('* operator', () => 'x' * 1000);
  });
}

Run a quick comparison from the project root.

dart run microbench --quick

The runner discovers *_benchmark.dart files under benchmark/ and compiles them to native executables. To run just this file, add benchmark/string_benchmark.dart to the command.

The first row is the baseline. In this example, the ratios show how much faster each variant ran than + operator on one machine.

Repeat one char, 1000 times  Rate
  + operator                 8.57K ops/s
  StringBuffer               57.79K ops/s (6.74x faster)
  * operator                 684.09K ops/s [best] (79.82x faster)

benchmark also takes size (units processed per run, to show throughput), column (to compare the same rows over several inputs), and setup and teardown callbacks that run outside the timed part. Nested groups join their names.

For a walkthrough of setup, timing, and the output, see Your first benchmark.

Choosing a benchmark API

Use case API Runnable example
Declare named benchmarks with shared inputs or untimed setup group and benchmark Benchmark suite
Compare rows over several inputs benchmark(..., column:) Benchmark suite
Compare closures on one input and inspect the result immediately compare Sync and async comparisons
Compare each variant across several input sizes matrix Sorting by input size
Reuse a benchmark with its own setup and teardown SyncBenchmark or AsyncBenchmark Benchmark classes
Build a table with several groups or skipped cells runComparison Comparison tables

One import, package:microbench/microbench.dart, has all of it and runs on every platform. package:microbench/io.dart adds report-file helpers for native runtimes. In a file that also imports package:test, hide one of the two group functions.

Use Metric.runtime for time per operation or Metric.rate for operations per second. For throughput, supply the number of bytes processed per run. For another unit, pair the amount of work with a metric such as Metric.perSecond('items').

🖥️ Command-line options

Pass options directly to the runner. For example, this verifies the variants in matching groups and writes a Markdown report from one benchmark file.

dart run microbench --quick --verify --out=BENCHMARK.md benchmark/string_benchmark.dart
Option Effect
--quick / --thorough short trial runs / long runs for close calls
--filter=REGEX only rows whose title / group / row matches
--format=FORMAT text, md, html, json, or a name you registered
--out=FILE also write the tables to FILE; the extension picks the format
--verify fail if the rows of a group return different results
--save=FILE save every result as JSON lines
--baseline=FILE compare with saved results; exit code 1 on a regression
--threshold=PCT smallest change --baseline reports (default 5)
--target=LIST runner only: jit, aot, js, wasm (default aot)

A plain main() receives options from the runner, whether it declares benchmarks or calls compare and runComparison directly. When invoking a file directly with dart run <file>, wrap the body in runMain(args, body) to read its command-line arguments. The runner also accepts custom program arguments after --. dart run microbench help lists everything. Running benchmarks

🎯 Trusting the numbers

The variants of a group are measured together. They warm up in turns until each one stops getting faster, then are timed in batches of about 10 ms, over rounds that alternate their order so gradual changes in machine load affect them all alike. Every variant goes through the same timing loop, and its results are kept where the compiler cannot discard them. Each cell reports the low end of its batch times: the cost of the work itself, which holds steady while the median moves with whatever else the machine is doing. A table warns when its samples varied too much to trust. Use --quick while building a benchmark and --thorough to investigate a close result.

[best] marks the best measured score in a column. A row can also show ≈ same when its samples do not differ significantly from the baseline at the configured level. Check that both variants do equivalent work with --verify, and repeat close comparisons on representative inputs. Reading the results · How microbench measures

📉 Catching regressions

Save a baseline on the reference revision. After changing the code, run the same file on the same machine, SDK, and runtime.

dart run microbench --save=before.jsonl benchmark/string_benchmark.dart
# On the candidate revision
dart run microbench --baseline=before.jsonl benchmark/string_benchmark.dart

The candidate exits with code 1 if the time per run increases by more than the threshold (5% by default) and the samples show a significant difference. With too few samples for the test, the threshold alone determines the verdict. If both runs are already saved, compare them without measuring again.

dart run microbench diff --threshold=5 before.jsonl after.jsonl

Give each program and runtime its own report path when saving multiple runs. If the two runs used a different runtime, SDK or operating system, the diff warns that the times are not comparable. Regressions and CI

🌍 Every runtime

The runner defaults to native AOT. Select one target or a comma-separated list to measure the same file on several runtimes.

dart run microbench --target=jit,aot,js,wasm --quick benchmark/string_benchmark.dart

The JS and Wasm targets run on Node.js. Wasm requires a Dart SDK with dart compile wasm and Node.js 22 or later. For web targets, select a console format with --format. File options such as --save and --out require a native runtime.

📝 Report files (VM only)

Use --out=BENCHMARK.md or --out=results.html to write a formatted table. For a report with your own headings or environment details, use ReportFile and environmentSummary(). Report example · Custom tables and reports

🍳 Examples

The quickstart example runs as written. Explore the other examples by task.

Example Shows
suite_example.dart benchmark()/group() in a plain main: nested groups, setup, throughput, columns
compare_example.dart compare with sync and async closures, verify, using the returned table
matrix_example.dart matrix over input sizes, with a custom unit (items/s)
class_example.dart SyncBenchmark/AsyncBenchmark classes, raw Measurement statistics, measureDiff
table_example.dart runComparison with groups and columns, skipped cells, a custom Metric, every renderer
custom_renderer_example.dart a TableRenderer of your own (CSV)
settings_example.dart BenchmarkSettings to configure a block from code and collect its tables
regression_example.dart saving results as JSON and BenchmarkDiff against them
report_example.dart ReportFile and environmentSummary (VM only)

📚 Guides

Follow the guide index in order, or start with the task at hand.

Level Guides
Beginner Your first benchmark · Reading the results
Intermediate Writing good benchmarks · Running benchmarks
Advanced Regressions and CI · Custom tables and reports · How microbench measures
Migration Migrating from benchmark_harness

📄 License

BSD 3-Clause License. See the LICENSE file for details. Issues and contributions are welcome at github.com/bitanon/microbench.

Libraries

io
Report files, on platforms with dart:io (not the web): stream tables into a file with ReportFile, and describe the machine with environmentSummary.
microbench
Microbenchmarks for Dart: declare benchmarks like tests, compare implementations side by side, and catch regressions.