"I made it faster" is a claim, not a fact, until you've measured it. A Stopwatch around a loop gives you a number, but not a trustworthy one: the JIT warms up, the garbage collector runs at random moments and the compiler can remove work whose result you ignore. BenchmarkDotNet handles all of that. This post sets it up, reads the results, and covers the mistakes that make benchmarks lie.
Why a Stopwatch isn't enough
A quick timing misses several things:
- JIT warm-up: the first calls run slower while code is compiled and tiered up.
- Garbage collection: a collection in the middle of one run makes it look slow.
- Dead code elimination: if nothing uses the result, the compiler may skip the work entirely.
- Noise: one run tells you nothing about the spread.
BenchmarkDotNet runs warm-up iterations, runs your code many times in a separate process, removes outliers, and reports the mean, the error and the standard deviation.
Set up a benchmark project
Keep benchmarks in their own console project so they never ship with the app:
dotnet new console -n Shop.Benchmarks
cd Shop.Benchmarks
dotnet add package BenchmarkDotNet
dotnet add reference ../Shop/Shop.csprojusing BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
BenchmarkRunner.Run<SlugBenchmarks>();
[MemoryDiagnoser]
public class SlugBenchmarks
{
private const string Title = "C# 14 & .NET 10: What's New in Extension Members";
[Benchmark(Baseline = true)]
public string RegexVersion() => SlugRegex.Generate(Title);
[Benchmark]
public string SpanVersion() => SlugSpan.Generate(Title);
}Run it in Release, without a debugger attached:
dotnet run -c ReleaseBenchmarks in Debug mode measure the debugger, not your code. BenchmarkDotNet warns you, but it's worth knowing why.
Read the results
A typical result looks like this (illustrative numbers; yours depend on the code and the machine):
| Method | Mean | Error | StdDev | Ratio | Gen0 | Allocated | Alloc Ratio |
|------------- |---------:|--------:|--------:|------:|-------:|----------:|------------:|
| RegexVersion | 1.842 us | 0.021us | 0.019us | 1.00 | 0.0477 | 408 B | 1.00 |
| SpanVersion | 0.211 us | 0.002us | 0.002us | 0.11 | 0.0153 | 128 B | 0.31 |- Mean: the average time per call.
- Error and StdDev: how much the measurements spread. If the error is a large share of the mean, the result is noisy; close other programs and run again.
- Ratio: compared with the method marked
Baseline = true. - Allocated: bytes allocated per call, from
[MemoryDiagnoser]. Less allocation means less garbage collection under load, which often matters more than raw speed in a web app.
In this example the span version is about nine times faster and allocates a third of the memory. A table like this, from your own run, is what belongs in a pull request.
Benchmark with realistic inputs
A benchmark on a 10-character string says little about 10 KB documents. Use [Params] to run each method across sizes:
[Params(10, 1_000, 100_000)]
public int Length { get; set; }
private string _input = "";
[GlobalSetup]
public void Setup() => _input = new string('a', Length);[GlobalSetup] runs once before measuring, so building test data isn't counted.
Return the result
Make each benchmark method return what it computes. BenchmarkDotNet consumes the return value, which stops the compiler from optimising the work away.
[Benchmark]
public int Sum() // returns the result: measured correctly
{
var total = 0;
foreach (var n in _numbers) total += n;
return total;
}A void method that computes something and drops it may be measuring an empty loop.
Compare runtimes
You can run the same benchmarks on two runtimes to see what an upgrade gives you for free:
[SimpleJob(RuntimeMoniker.Net80, baseline: true)]
[SimpleJob(RuntimeMoniker.Net10_0)]
[MemoryDiagnoser]
public class JsonBenchmarks { /* … */ }The benchmark project must target both frameworks for this (<TargetFrameworks>net8.0;net10.0</TargetFrameworks>).
Common mistakes
- Benchmarking I/O. Database and HTTP calls are dominated by the network. Benchmark the CPU-bound part; measure end-to-end latency with a load test instead.
- Shared state between runs. A list that grows on every iteration makes later runs slower. Reset it in
[IterationSetup], or better, avoid mutation. - Micro-optimising cold code. Shaving 200 nanoseconds off code that runs once per request is noise next to a 20-millisecond query. Profile first to find where time really goes.
- Trusting one machine. Laptops throttle on battery. Run important comparisons on a plugged-in machine with other apps closed.
Where it fits in a real project
- A profiler or slow-request log points to a hot method.
- Write a benchmark that reproduces it with realistic data.
- Change the code, run again, keep the change only if the numbers improve.
- Paste the table into the pull request.
Wrapping up
BenchmarkDotNet turns "it feels faster" into a table of numbers with error bars and allocations. Run in Release, return your results, use realistic inputs with [Params], and turn on [MemoryDiagnoser]. Then optimise only what the numbers say is worth it.