As developers, we are sometimes challenged with making a specific piece of code run quicker. We frequently need to pick which piece of code performs the best. Benchmarking gives us concrete measurements between different portions of code, allowing us to make verifiably right decisions based on performance.
In this article, I will show you how to add a Benchmark to your project. Follow these steps
Step1
Create a console application
Step2
Add BenchmarkDotnet Nuget package by running the following command.
dotnet add install BenchmarkDotNet
Step3
Create a class and create a public method and add the Benchmark
attribute
Baseline you can mark a benchmark method or a job as a baseline. {alertSuccess}
public class StringBenchmark
{
[Benchmark(Baseline =true)]
public void StringConcatTest()
{
var result = "";
for (int i = 0; i < 1000; i++)
{
result += $"Test {i}";
}
}
[Benchmark]
public void StringBuilderTest()
{
var result = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
result.Append($"Test {i}");
}
}
}
Step4
Open program.cs and add the following code
class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<StringBenchmark>();
}
}
Step 5
Open the command prompt and run the following command.
dotnet run -c Release
If you want to see memory related things like Garbage collection and memory allocation, then you add MemoryDiagnoser
at the class level.