BenchmarkDotNet for benchmarking performance
There is a popular benchmarking NuGet package for .NET that Microsoft uses in its blog posts about performance improvements, and newsletter and LinkedIn posters frequently use it to provide evidence for a faster approach to solving a .NET problem. It is therefore important for .NET developers to know how BenchmarkDotNet works and how to use it for their own performance testing.
Writing benchmarks is a bit like writing unit tests. You need to create a class with methods that represent different benchmark tests. With BenchmarkDotNet, you decorate the methods with the [Benchmark]
attribute. One of those methods must be set as the baseline using the [Benchmark(Baseline = true)]
attribute to which the other benchmark methods will be compared.
Let’s see how we could use it to compare performance between the string
concatenation (which will be our baseline) and StringBuilder
(which we expect will be an improvement):
- Use...