Writing trustworthy micro-benchmarks with BenchmarkDotNet on .NET 10: Release builds, warm-up and statistics, MemoryDiagnoser, baselines and ratios, Params, returning results to defeat dead-code elimination, and reading the results table.
BenchmarkDotNet turns a method into a properly measured experiment: it builds a separate Release process, does warm-up and pilot runs so tiered JIT has finished, runs many iterations and reports mean, error and standard deviation.
A correct benchmark:
Baseline = true, so you get a Ratio column;[MemoryDiagnoser] for allocated bytes per operation and GC counts;[GlobalSetup] from fields with [Params] for realistic sizes, not constants the JIT can fold;Then I check that the difference is bigger than the error, on a quiet machine, before believing it. The trade-off: a micro-benchmark proves one method is faster in isolation; it doesn't prove the endpoint is, so I confirm with production numbers.
"I never time code with a
Stopwatchin a loop, because it measures the JIT, the first-call costs and whatever else the machine is doing. BenchmarkDotNet does the boring statistics properly. It generates a separate project, builds it in Release, runs it in its own process, does a pilot phase to choose an iteration count, warms up so tiered compilation and Dynamic PGO have settled, then runs enough iterations to report a mean with a confidence interval.My benchmark class has a few non-negotiables. One method is marked
Baseline = true, so I read the Ratio column rather than raw nanoseconds that change from machine to machine.[MemoryDiagnoser]is always on, because on a server allocations often matter more than CPU time: the Allocated column tells me bytes per operation. Inputs come from fields filled in[GlobalSetup]with[Params], so I'm not measuring setup and the JIT can't fold constants, and I test realistic sizes, say 10, 1,000 and 100,000 items, because the winner often changes with size. And the work must be observable: the method returns its result, or consumes the sequence. If the result is thrown away, the JIT is free to drop the computation, and the number you get measures an empty method, not your code. A result that is suspiciously close to zero is the tell.The mistake I see is treating a benchmark as the end of the job. It proves that method A is faster than method B on that input, on a warm, quiet machine. Whether the endpoint is faster depends on how much of the request that method is, which you learn from a profile before and production metrics after."
| Attribute / API | Purpose |
|---|---|
[Benchmark(Baseline = true)] |
The reference; other methods get Ratio and Alloc Ratio |
[MemoryDiagnoser] |
Allocated bytes/op, Gen0/1/2 collections per 1,000 ops |
[Params(10, 1_000, 100_000)] |
Runs every benchmark for each value |
[GlobalSetup] / [IterationSetup] |
Prepare data once / per iteration (use the latter sparingly: it adds noise) |
[SimpleJob(RuntimeMoniker.Net10_0)] |
Pin or compare runtimes |
[ShortRunJob] |
Fewer iterations for quick checks, not for final numbers |
| Column | Meaning | What to check |
|---|---|---|
| Mean | Average time per operation | Compare with Error |
| Error | Half of the 99.9% confidence interval | If two means differ by less than this, call it a tie |
| StdDev | Spread | High = noisy machine, GC effects or thermal throttling |
| Ratio | Mean / baseline mean | 0.40 = 2.5× faster |
| Allocated | Bytes per operation | Often the real win on servers |
A team rewrote a CSV parser and claimed a 5× speed-up from a Stopwatch test. BenchmarkDotNet showed the old version was being measured on its first, unoptimised (Tier 0) run; the real gain was 1.6× in time but 92% fewer bytes allocated. In production, Gen 0 collections fell from 40/s to 6/s and import p95 dropped by 18%, which was the number the business cared about.
Checks that the candidate can produce trustworthy performance evidence rather than misleading timings.
Green flags
Red flags
first call : JIT Tier 0 compile + type loading + static ctors (slow, once)
next 30 calls: Tier 0 code, call counting (slower than final)
after ~30 : background Tier 1 rejit with Dynamic PGO (final speed)
any time : GC pauses, other processes, CPU frequency scaling
A Stopwatch loop mixes all of these. BenchmarkDotNet separates them.
The JIT optimises benchmark code like any other code. Two optimisations ruin benchmarks:
Dead-code elimination. If a value is computed and never used, and the computation has no side effects, the JIT may remove it:
[Benchmark]
public void Bad() { var x = Math.Sqrt(_value); } // x unused: may compile to nothing
[Benchmark]
public double Good() => Math.Sqrt(_value); // returned: BenchmarkDotNet consumes it
Constant folding. If the inputs are compile-time constants, the JIT may compute the answer once while compiling:
[Benchmark]
public double Bad() => Math.Sqrt(16.0); // can become 'return 4.0'
private double _value = 16.0; // a field read at run time
[Benchmark]
public double Good() => Math.Sqrt(_value);
Lazy sequences. return items.Where(f); only measures creating the iterator. Materialise it, or call .Consume(consumer) with BenchmarkDotNet's Consumer.
[MemoryDiagnoser] uses GC.GetAllocatedBytesForCurrentThread() around the workload (accurate per operation) and reports collections per 1,000 operations. Allocations measured are managed only; native allocations need other tools.
Results are only as good as the machine: close browsers and IDEs, plug in laptops (power-saving changes CPU frequency), avoid shared CI agents for final numbers, and compare runs on the same hardware. BenchmarkDotNet prints the environment (CPU, OS, runtime, GC mode) at the top of the report; keep it with the results. A high StdDev or a bimodal distribution warning usually means GC or the environment, not your code.
[SimpleJob(RuntimeMoniker.Net90)]
[SimpleJob(RuntimeMoniker.Net10_0, baseline: true)]
This is how you check what upgrading to .NET 10 gives a particular hot path. You can also compare environment variables such as DOTNET_TieredPGO=0 with custom jobs.
string.Join vs StringBuilder vs string.Concat with [Params(3, 100)] and see the winner change.Bad() and Good() pairs above and compare the numbers.items.Where(...).Select(...) without consuming it, then with .ToList().[SimpleJob(RuntimeMoniker.Net90)] and Net10_0 jobs to an existing benchmark and compare.--filter *Parse* from the command line and export results with --exporters markdown.Comparing a LINQ-based and a span-based way to sum the numbers in a comma-separated line, measured properly.
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
namespace Perf.Benchmarks;
[MemoryDiagnoser] // Allocated bytes/op and GC counts
[SimpleJob(RuntimeMoniker.Net10_0)]
public class SumCsvBenchmarks
{
[Params(10, 1_000)] // the winner can change with size
public int Count { get; set; }
private string _line = "";
[GlobalSetup] // setup is not measured
public void Setup() =>
_line = string.Join(',', Enumerable.Range(1, Count));
[Benchmark(Baseline = true)]
public long Linq() => // returns its result: no dead-code elimination
_line.Split(',').Select(long.Parse).Sum();
[Benchmark]
public long Span()
{
long total = 0;
foreach (var range in _line.AsSpan().Split(',')) // .NET 9+ MemoryExtensions.Split
{
total += long.Parse(_line.AsSpan()[range]);
}
return total;
}
}
public static class Program
{
// dotnet run -c Release -- --filter *SumCsv*
public static void Main(string[] args) =>
BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args);
}
The shape of the output (illustrative; your numbers depend on hardware):
| Method | Count | Mean | Error | Ratio | Allocated | Alloc Ratio |
|------- |------ |-----------:|----------:|------:|----------:|------------:|
| Linq | 10 | 210.0 ns | 2.1 ns | 1.00 | 656 B | 1.00 |
| Span | 10 | 74.0 ns | 0.6 ns | 0.35 | - | 0.00 |
| Linq | 1000 | 24,800 ns | 190 ns | 1.00 | 56,552 B | 1.00 |
| Span | 1000 | 9,300 ns | 70 ns | 0.38 | - | 0.00 |
Stopwatch loop. Why it is wrong: You measure JIT tiers, first-call costs and noise. Instead: Use BenchmarkDotNet, and a profile to choose what to benchmark.Consumer.dotnet run -c Release without a debugger.[MemoryDiagnoser]. Why it is wrong: On servers, allocations drive GC and tail latency even when Mean looks the same. Instead: Always report Allocated.[IterationSetup] for cheap setup. Why it is wrong: It forces one invocation per iteration and adds noise for fast methods. Instead: Prefer [GlobalSetup].I treat a benchmark as evidence in a pull request, not a trophy: the PR shows the profile that made the method worth optimising, the BenchmarkDotNet table with Mean, Error and Allocated, and afterwards the production metric that moved. Teams that keep a small benchmark project in the repo and run it in CI against a baseline catch regressions early, but CI machines are noisy, so I only fail builds on large, repeatable changes (say over 20%) and track the rest as trends.
| Measurement | When it fits | Cost | When not to |
|---|---|---|---|
| BenchmarkDotNet | Comparing implementations of a hot method | Minutes per run | Questions about I/O, contention or the whole endpoint |
| Load test (k6, Azure Load Testing) | Endpoint throughput and percentiles | Environment and data setup | Choosing between two string-parsing approaches |
| Production metrics | The final verdict | Needs a release | Early design choices |
First I prove the method is hot: dotnet-counters shows a high allocation rate and an allocation profile points at it. Then I write a BenchmarkDotNet benchmark with [MemoryDiagnoser] so every change shows Mean and Allocated bytes.
The usual fixes:
ReadOnlySpan<char> slicing instead of Substring and Split, which allocate a string per piece.string.Create (or stackalloc plus TryFormat) to build the final string once.ArrayPool<T>.Shared for temporary buffers, returned in finally.The trade-off is readability: span-based code is harder to maintain, so I only do it where the profile and the benchmark justify it.
I treat performance as an experiment, not a hunch. First I agree a goal as a number: for example p95 under 200 ms at 300 requests a second. Then I measure a baseline with the same tools I'll use to verify: Application Insights for request and dependency timings, dotnet-counters for CPU, GC and ThreadPool, and a repeatable load test.
Next I find the bottleneck: is time going to CPU, garbage collection, waiting on I/O (database, HTTP) or waiting on locks? Only then do I change one thing, re-run the same measurement and keep the change only if the numbers moved. I stop once the goal is met.
The trade-off is time: measuring first feels slower, but guessing usually optimises code that wasn't the problem.
Last updated 23 Nov 2026.