Skip to main content

microbench 0.1.0 copy "microbench: ^0.1.0" to clipboard
microbench: ^0.1.0 copied to clipboard

Zero-dependency microbenchmark harness for Dart: robust timing, comparison tables in Markdown, HTML or text, JSON output, and README embedding.

example/example.dart

// Copyright (c) 2026, Sudipto Chandra
// All rights reserved. Check LICENSE file for details.

import 'package:microbench/microbench.dart';

/// Joins [count] short strings with `+`.
class ConcatBenchmark extends SyncBenchmark {
  ConcatBenchmark(this.count) : super('+ operator', count);

  final int count;

  @override
  Object? run() {
    var s = '';
    for (var i = 0; i < count; i++) {
      s += 'x';
    }
    return s;
  }
}

Future<void> main() async {
  const options = BenchmarkOptions.quick;

  // 1. One benchmark, one line.
  await ConcatBenchmark(1000).measureRate(
    options: options,
    metric: Metric.perSecond('chars'),
  );

  // 2. A quick side-by-side comparison in the terminal.
  await ConcatBenchmark(1000).measureDiff(
    [
      SyncBenchmark.from(
        'StringBuffer',
        () => (StringBuffer()..writeAll(List.filled(1000, 'x'))).toString(),
        size: 1000,
      ),
    ],
    options: options,
    metric: Metric.perSecond('chars'),
  );

  // 3. A full table: one group per approach family, one column per size.
  //    Rows are compared with the first row of their group.
  const sizes = [10, 1000];
  final table = await runComparison(
    title: 'Building a string',
    columns: [for (final n in sizes) '$n chars'],
    groupHeader: 'Task',
    rowHeader: 'Approach',
    metric: Metric.perSecond('chars'),
    options: options,
    groups: {
      'Repeat one char': (c) => [
            ConcatBenchmark(sizes[c]),
            SyncBenchmark.from(
              'StringBuffer',
              () {
                final sb = StringBuffer();
                for (var i = 0; i < sizes[c]; i++) {
                  sb.write('x');
                }
                return sb.toString();
              },
              size: sizes[c],
            ),
            SyncBenchmark.from('* operator', () => 'x' * sizes[c],
                size: sizes[c]),
          ],
    },
  );

  // Render the same results in any format.
  print(const TextTableRenderer().render(table));
  print(const MarkdownTableRenderer().render(table));
}
1
likes
0
points
0
downloads

Publisher

verified publisherbitanon.dev

Weekly Downloads

Zero-dependency microbenchmark harness for Dart: robust timing, comparison tables in Markdown, HTML or text, JSON output, and README embedding.

Repository (GitHub)
View/report issues

Topics

#benchmark #performance #profiling #testing

Funding

Consider supporting this project:

paypal.me

License

unknown (license)

More

Packages that depend on microbench