Benchmarking with BenchmarkDotNet
Write accurate micro-benchmarks with BenchmarkDotNet, analyze throughput and allocations, and avoid common pitfalls.
Why BenchmarkDotNet?
Micro-benchmarking is surprisingly hard: JIT warm-up, GC pauses, CPU caches, and OS scheduling all introduce noise. BenchmarkDotNet handles all of this automatically and produces statistically reliable results.
Installing and First Benchmark
Add the NuGet package, create a class with [Benchmark] methods, and run with BenchmarkRunner.Run. Always run benchmarks in Release mode.
// dotnet add package BenchmarkDotNet
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
[MemoryDiagnoser] // report allocations
[RankColumn] // rank methods by speed
public class StringBenchmarks
{
[Benchmark(Baseline = true)]
public string Concatenation()
{
var s = "";
for (int i = 0; i < 100; i++) s += i;
return s;
}
[Benchmark]
public string StringBuilder()
{
var sb = new System.Text.StringBuilder();
for (int i = 0; i < 100; i++) sb.Append(i);
return sb.ToString();
}
}
// Program.cs (must run as Release):
BenchmarkRunner.Run<StringBenchmarks>();All lessons in this course
- Native AOT Compilation
- Trimming & Reflection Limitations
- ReadyToRun & Tiered Compilation
- Benchmarking with BenchmarkDotNet