BenchmarkDotNet for C# (.NET): Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is BenchmarkDotNet and why is it needed?

\n\n

BenchmarkDotNet is a powerful, cross-platform open-source library for .NET, designed for precise code performance measurement (benchmarking). In software development, it is often necessary to compare two or more approaches to solving the same problem: which sorting algorithm is faster, which string formatting method is more efficient, how does using different data structures affect application speed. BenchmarkDotNet solves this problem at a professional level.

\n\n

Why is it needed? Manual time measurement using Stopwatch is fraught with many errors: the influence of background processes like JIT compilation, garbage collection (GC), CPU cache warm-up, and system timer inaccuracies. BenchmarkDotNet automatically performs:

\n
    \n
  • Warmup: Runs the code several times before measurement to stabilize the JIT compiler and CPU cache.
  • \n
  • Multiple runs (Iterations): Executes the method many times and collects statistics.
  • \n
  • Statistical analysis: Calculates mean, median, standard deviation, minimum and maximum time.
  • \n
  • Isolation: Runs each benchmark in a separate process to minimize the influence of other tests.
  • \n
  • Diagnostics: Can measure not only time but also memory allocation (Allocated), number of garbage collections (GC Collections), and other metrics.
  • \n
\n

Without BenchmarkDotNet, you risk getting unreliable results and making incorrect conclusions about code optimization.

\n\n

Installing BenchmarkDotNet

\n\n

Installing the BenchmarkDotNet library into a .NET project (C#, F#, VB.NET) is done via the NuGet package manager. There are three main ways:

\n\n

1. Via .NET CLI (recommended)

\n

Open a terminal in the root folder of your project and run the command:

\n
dotnet add package BenchmarkDotNet
\n\n

2. Via Package Manager Console in Visual Studio

\n

Open the menu Tools -> NuGet Package Manager -> Package Manager Console and run:

\n
Install-Package BenchmarkDotNet
\n\n

3. Via NuGet graphical interface in Visual Studio

\n

Right-click on the project in Solution Explorer, select "Manage NuGet Packages", find "BenchmarkDotNet" and click "Install".

\n\n

Important: For correct operation, the library requires the project to be built in Release configuration. Debug configuration does not optimize code, which will lead to distorted results.

\n\n

Quick start with code example

\n\n

Let's write a simple benchmark that compares two ways of string concatenation: using the + operator and using StringBuilder.

\n\n

1. Create a new .NET console project: dotnet new console -n MyBenchmark.

\n

2. Install the library: dotnet add package BenchmarkDotNet.

\n

3. Replace the contents of the Program.cs file with the following code:

\n\n
using BenchmarkDotNet.Attributes;\nusing BenchmarkDotNet.Running;\nusing System.Text;\n\npublic class StringConcatenationBenchmark\n{\n    private const int N = 1000; // Number of iterations inside the method\n\n    [Benchmark]\n    public string UsingPlusOperator()\n    {\n        string result = "";\n        for (int i = 0; i < N; i++)\n        {\n            result = result + "a";\n        }\n        return result;\n    }\n\n    [Benchmark]\n    public string UsingStringBuilder()\n    {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < N; i++)\n        {\n            sb.Append("a");\n        }\n        return sb.ToString();\n    }\n}\n\npublic class Program\n{\n    public static void Main(string[] args)\n    {\n        var summa                    

Recommendations