Back to all posts
·8 min read

Measuring .NET performance with BenchmarkDotNet: reliable data instead of guesses

Performance discussions in a team usually start with a hunch: "This Split call allocates too much," "LINQ is slow here," "if we cache that dictionary it will be faster." Hunches are sometimes right, but in a code review it is the measurement that convinces, not the hunch. The trouble is that measuring the speed of a small piece of code correctly in .NET is much harder than it looks at first.

In this post I explain why micro-measurements should not be done by hand, how to set up a reliable benchmark with BenchmarkDotNet, how to read its output, and which traps quietly ruin a measurement. The goal is not to optimise every line; it is to base the decision on data once you have found a place that is worth optimising.

Why Stopwatch is not enough

The most natural first attempt is to run the code in a loop and time it with Stopwatch. This approach produces misleading results for several reasons.

The first call includes JIT compilation. .NET also uses tiered compilation: a method is first compiled in a fast but lightly optimised form, and after it has been called often enough it is replaced by a better optimised version. A short loop leaves it unclear which version you are actually measuring.

The garbage collector interferes as well. Memory allocated by one method may be collected while another method is being measured, attributing the time to the wrong place. The operating system scheduler, background processes and CPU frequency changes add noise. Measuring a Debug build makes the results entirely meaningless.

You can manage all of this by hand, but it is tedious and error-prone. BenchmarkDotNet does it for you: it runs each benchmark in a separate process, performs warm-up rounds, collects enough measurements and summarises the result statistically.

Setting up the first benchmark

Keeping benchmarks in a separate console project is the cleanest approach. After adding the BenchmarkDotNet package, you write the methods you want to measure in a class. The following example compares two ways of summing the numbers in a comma-separated line:

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

BenchmarkRunner.Run<LineParsingBenchmarks>();

[MemoryDiagnoser]
public class LineParsingBenchmarks
{
    private string _line = "";

    [Params(4, 64)]
    public int FieldCount { get; set; }

    [GlobalSetup]
    public void Setup() =>
        _line = string.Join(',', Enumerable.Range(0, FieldCount).Select(i => i * 7));

    [Benchmark(Baseline = true)]
    public int SumWithSplit()
    {
        var sum = 0;
        foreach (var part in _line.Split(','))
            sum += int.Parse(part);
        return sum;
    }

    [Benchmark]
    public int SumWithSpan()
    {
        var sum = 0;
        var rest = _line.AsSpan();
        while (true)
        {
            var comma = rest.IndexOf(',');
            sum += int.Parse(comma < 0 ? rest : rest[..comma]);
            if (comma < 0) return sum;
            rest = rest[(comma + 1)..];
        }
    }
}

Always run the project in the Release configuration: dotnet run -c Release. BenchmarkDotNet warns you when it detects a Debug build; that warning deserves to be taken seriously.

Once the number of benchmarks grows, using BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args) instead of BenchmarkRunner.Run pays off. You can then use the --filter argument to run only the benchmarks you care about, without waiting for the entire suite on every attempt.

Reading the output

BenchmarkDotNet presents its results as a table. These are the columns I look at most:

  • Mean: the average duration across all measurements. It is not enough on its own, but it is the starting point for comparison.
  • Error and StdDev: show how stable the measurement is. If the standard deviation is large relative to the mean, the measurement is noisy, and a small difference between two methods may not be meaningful.
  • Ratio: the ratio relative to the method marked with Baseline = true. It makes the comparison readable at a glance.
  • Allocated: with [MemoryDiagnoser] added, the memory allocated per operation. Columns such as Gen0 show how often garbage collection happens.

The memory columns are often more instructive than the timings. Even if one method looks slightly faster in isolation, if it allocates much more memory, the difference will surface elsewhere in a real application as extra work for the garbage collector. In a high-traffic API, reducing allocations can be worth more than a small gain in average duration.

Another habit: do not read the result only as "which one is faster." Looking at how the difference changes across the input sizes you provide with [Params] shows how a method scales. A difference that is negligible for small inputs can become significant for large ones, or the other way round.

Traps that quietly ruin a measurement

BenchmarkDotNet sets up the measurement infrastructure correctly, but the content of the benchmark is your responsibility. These are the mistakes I run into most often:

Not using the result. If a benchmark method does not return the value it computes, the JIT compiler may decide the computation is unnecessary and remove it partly or entirely. You then end up measuring code that does nothing. Returning the result removes this risk; BenchmarkDotNet consumes the returned value.

Including the preparation in the measurement. If you create test data inside the benchmark method, you also measure the cost of producing it. Data that only needs to be prepared once belongs in [GlobalSetup]. For state that must be reset before each invocation there is [IterationSetup], but it should be used carefully because it can distort measurements of very short operations.

Constant inputs. The compiler can precompute operations on values that are known at compile time. Providing the input through a field or [Params] ensures the code under measurement actually runs.

Unrealistic data. Measuring with the same short string every time, or with a small collection that always fits in the cache, may not reflect production behaviour. The size and distribution of the input should be close to the data the application really sees.

A noisy environment. Watching a video in the browser, running a build, or using a laptop in power-saving mode while measuring makes the results fluctuate. When comparing two methods, measure both in the same run, under the same conditions.

Profile first, then benchmark

A micro-benchmark answers a question; it does not find the problem. If an API request is slow, instead of assuming the cause is a text-parsing method, you first need a profile: distributed traces, database query durations, the CPU and memory breakdown from a profiler. Very often the bottleneck is a network call, a missing index or a query that is repeated needlessly. None of these is fixed by a micro-benchmark.

The right place for a benchmark is comparing alternatives while improving a hot code path the profile has pointed to. For example, a serialisation step called thousands of times per second, a routing rule or a validation function. Writing a few alternatives in such a place and measuring them lets you show a concrete table in a code review instead of saying "I think this is faster."

You also need to verify separately how much of a micro-benchmark gain carries over to the application as a whole. Making a method twice as fast may go unnoticed by users if that method accounts for only a small part of the request's total time. That is why profiling again after the change, or measuring end to end with a load test, is a good final step.

Turning benchmarks into a lasting tool

One-off benchmarks are useful, but they become even more valuable when they are kept in the codebase. I keep benchmark projects in the solution, next to the test projects. Someone who changes a critical path can run the relevant benchmark before and after the change and add the result to the pull request description. This moves performance discussions away from personal opinion and onto common ground.

Running benchmarks automatically in the continuous integration pipeline looks tempting, but shared build machines are noisy. An automatic threshold that tries to catch small differences can produce frequent false alarms. My preference is to verify in CI only that the benchmarks compile and run without errors using a short configuration, and to do the real comparison on a quiet machine when needed. If long-term performance tracking is required, a dedicated environment with fixed hardware gives more reliable results.

Finally, it is important to store results together with their context. BenchmarkDotNet writes the operating system, processor and runtime information at the top of its output. Directly comparing results taken on different machines or different runtime versions is misleading; a comparison is only meaningful between measurements taken in the same environment.

Closing

Performance improvement comes down to finding the right place and making the right decision there. The profile shows the right place; a reliable measurement supports the right decision. BenchmarkDotNet makes the second step easier by taking on the tedious parts such as warm-up, process isolation and statistics. The remaining responsibility is ours: writing benchmarks that use their result, keep preparation out of the measurement and work with realistic data, and reading the resulting table not just by its mean but together with deviation and allocations. Once that habit settles in, the phrase "I think it's faster" slowly disappears from code reviews.