Benchmarks

suggest change

Accurately measuring the execution speed and memory allocations of C# code is deceptively complex. Naive timing with System.Diagnostics.Stopwatch often yields deceptive results due to JIT compilation warmup, tiered compilation (Tier 0 vs. Tier 1), dead-code elimination, and Garbage Collector (GC) interference.

In the .NET ecosystem, BenchmarkDotNet is the gold standard benchmarking framework used by the .NET Runtime team and major open-source libraries.


1. Setting Up BenchmarkDotNet

Create a dedicated console application and install the library:

dotnet new console -n Benchmarks
cd Benchmarks
dotnet add package BenchmarkDotNet

Ensure the test project is always compiled and executed in Release mode:

dotnet run -c Release

2. Writing a Benchmark Class

A benchmark is a public class containing methods decorated with the [Benchmark] attribute:

using System.Security.Cryptography;
using System.Text;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

[MemoryDiagnoser] // Measures allocated bytes and GC Gen 0/1/2 collections
public class HashComparisonBenchmark
{
    private byte[] _data = null!;
    private SHA256 _sha256 = null!;
    private MD5 _md5 = null!;

    [GlobalSetup]
    public void Setup()
    {
        _data = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog");
        _sha256 = SHA256.Create();
        _md5 = MD5.Create();
    }

    [GlobalCleanup]
    public void Cleanup()
    {
        _sha256.Dispose();
        _md5.Dispose();
    }

    [Benchmark(Baseline = true)] // Reference baseline for comparison
    public byte[] ComputeSha256()
    {
        return _sha256.ComputeHash(_data);
    }

    [Benchmark]
    public byte[] ComputeMd5()
    {
        return _md5.ComputeHash(_data);
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Executes warmup iterations, measurement runs, and outputs statistical table
        BenchmarkRunner.Run<HashComparisonBenchmark>();
    }
}

3. Parameterized Benchmarks with [Params]

You can test how algorithmic complexity scales as input size increases using [Params]:

using System;
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;

[MemoryDiagnoser]
public class ListSearchBenchmark
{
    [Params(100, 1_000, 10_000)]
    public int Size { get; set; }

    private List<int> _list = null!;
    private HashSet<int> _set = null!;
    private int _target;

    [GlobalSetup]
    public void Setup()
    {
        _list = new List<int>(Size);
        _set = new HashSet<int>(Size);
        for (int i = 0; i < Size; i++)
        {
            _list.Add(i);
            _set.Add(i);
        }
        _target = Size - 1; // Worst-case scenario for linear search
    }

    [Benchmark(Baseline = true)]
    public bool SearchList() => _list.Contains(_target);

    [Benchmark]
    public bool SearchHashSet() => _set.Contains(_target);
}

Sample output (timings vary by machine):

| Method        | Size  | Mean        | Error     | StdDev    | Ratio | RatioSD | Allocated | Alloc Ratio |
|-------------- |------ |------------:|----------:|----------:|------:|--------:|----------:|------------:|
| SearchList    | 100   |   42.150 ns | 0.4120 ns | 0.3854 ns |  1.00 |    0.01 |         - |          NA |
| SearchHashSet | 100   |    6.120 ns | 0.0510 ns | 0.0477 ns |  0.15 |    0.00 |         - |          NA |
|               |       |             |           |           |       |         |           |             |
| SearchList    | 1000  |  418.300 ns | 3.1200 ns | 2.9185 ns |  1.00 |    0.01 |         - |          NA |
| SearchHashSet | 1000  |    6.210 ns | 0.0490 ns | 0.0458 ns |  0.01 |    0.00 |         - |          NA |

4. Comparing String Concatenation and Memory

using System.Text;
using BenchmarkDotNet.Attributes;

[MemoryDiagnoser]
public class StringFormattingBenchmark
{
    private const string FirstName = "Jane";
    private const string LastName = "Doe";
    private const int Age = 32;

    [Benchmark(Baseline = true)]
    public string ConcatenationPlus()
    {
        return FirstName + " " + LastName + " is " + Age.ToString() + " years old.";
    }

    [Benchmark]
    public string StringInterpolation()
    {
        return $"{FirstName} {LastName} is {Age} years old.";
    }

    [Benchmark]
    public string StringBuilderUsage()
    {
        var sb = new StringBuilder();
        sb.Append(FirstName).Append(' ').Append(LastName).Append(" is ").Append(Age).Append(" years old.");
        return sb.ToString();
    }
}

5. Benchmarking Multiple .NET Runtimes

You can verify performance across multiple target frameworks (e.g. .NET 6 vs .NET 8 vs .NET 9) within the same benchmark:

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;

[SimpleJob(RuntimeMoniker.Net80)]
[SimpleJob(RuntimeMoniker.Net90)]
[MemoryDiagnoser]
public class RuntimeComparison
{
    [Benchmark]
    public string FastPath()
    {
        // Tests improvements in modern .NET JIT or BCL algorithms
        return string.Join(',', new[] { "A", "B", "C", "D" });
    }
}

The project must target every runtime you compare, otherwise those jobs fail to build:

<TargetFrameworks>net8.0;net9.0;net10.0</TargetFrameworks>

Then pick the host framework when running: dotnet run -c Release -f net10.0.


6. Avoiding Common Micro-benchmarking Pitfalls

  1. Dead Code Elimination: If the JIT compiler detects that a benchmarked computation's result is never used, it may delete the entire loop. Always return the computed result from the [Benchmark] method so the return value is consumed by BenchmarkDotNet.
  2. Never Run in Debug: BenchmarkDotNet will refuse to execute under a Debug build by default. Debug builds omit method inlining, loop unrolling, and emit extra no-op instructions.
  3. Avoid Side Effects in Benchmarks: Ensure benchmark methods are deterministic and do not mutate state that affects subsequent iterations unless using [IterationSetup] and [IterationCleanup].
  4. Isolate Environment: Close resource-heavy desktop applications (browsers, music players, background downloads) and plug laptops into AC power to avoid CPU thermal throttling.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents