Measuring Code Performance with BenchmarkDotNet in .NET

Ramy Elnaghy
3 min readOct 5, 2023

--

Introduction

Performance optimization is a critical aspect of software development, regardless of the developer’s experience level or the type of application being developed. Measuring and understanding the performance of code is essential to identifying code issues and implementing effective optimizations. This article will teach you how to use the BenchmarkDotNet library in .NET to benchmark and measure the performance of your code.

What is BenchmarkDotNet?

BenchmarkDotNet is a powerful open-source library for benchmarking .NET code. It allows you to precisely measure the execution time of your code, helping you identify bottlenecks and make informed performance improvements. Let’s dive into how to use it.

Getting Started

To get started with BenchmarkDotNet, we will create a console application then you need to install BenchmarkDotNet using NuGet Package Manager:

dotnet add package BenchmarkDotNet

Creating a Benchmark Class

Let’s create a benchmark class for our demonstration. We will focus on a list of statements and evaluate various approaches for retrieving statements that include a specific word.

  1. Add a benchmark public class with the name TextSearchBenchmark
  2. Add a list of strings inside the class.

Configuring the Benchmark

The [GlobalSetup] method initializes the list with sample statements.

We can also use the [Params] attribute to specify different list sizes to test, however for simplicity we will use a fixed-size list in this example.

Benchmark Methods

In this example, we have two benchmark methods: FindStatementByValue, and FirstOrDefaultStatementByValue. We'll compare their performance for a fixed list size of 500 statements.

Running the Benchmark

To run the benchmark, go to Program class, and call the BenchmarkRunner as shown below.

go to the application root directory, open PowerShell, and build the application using the dotnet command in the Release mode.

use the dotnet command to run the application by executing the main dll library.

Hit enter to start the benchmarking process.

  • WorkloadPilot is the code you want to measure.
  • OverheadWarmup and OverheadActual account for the time and resources consumed by BenchmarkDotNet itself.
  • WorkloadWarmup measures the time it takes for your code to stabilize during the warm-up phase.
  • WorkloadActual measures the actual performance of your code once it has reached a stable state.

Result Summary Section

In the summary section, you’ll notice the two methods we are comparing, along with their performance metrics. The most important metric is the mean measure, which is the average time it takes to run each method.

Happy Coding!

--

--