Skip to content

Benchmarking

Context: Benchmarking measures the performance (execution time, memory allocations) of code to identify bottlenecks and compare implementations. Manual timing with Stopwatch is error‑prone because of JIT warm‑up, background threads, and other factors. BenchmarkDotNet is the industry‑standard library for .NET benchmarking that handles all these complexities.

using System;
using System.Diagnostics;
// Manual benchmarking (not recommended)
public class ManualBenchmark
{
public static void Measure(Action action)
{
Stopwatch sw = Stopwatch.StartNew();
action();
sw.Stop();
Console.WriteLine($"Elapsed: {sw.ElapsedMilliseconds} ms");
}
}
Terminal window
dotnet run
Elapsed: 123 ms
  • Always use a dedicated benchmarking library.
  • Run benchmarks in Release mode without debugger attached.

Choosing a collection type – Benchmark whether List<T> or HashSet<T> is faster for your specific lookup pattern.
See BenchmarkDotNet documentation.