☰ Brand

Persian Programmer

Persian Programmer ×
Home About Us Services and Pricing Contact Us My Resume Co-worker

Benchmarking in C# Using BenchmarkDotNet

Benchmarking in C# Using BenchmarkDotNet

What is benchmarking

Why benchmarking

Benchmarking in C#

Demo

public class DictionaryLookup
{
   readonly Dictionary<string, string> MyDictionary = new();
   
   public DictionaryLookup()
   {
     for(int i =0;i < 100; i++)
     {
       MyDictionary[i.ToString()] = $"test_{i}";
     }
   }
}
public string GetValueByKey(string key)
{
    if (MyDictionary.ContainsKey(key))
    {
      return MyDictionary[key];
    }
    return null;
}
public string GetValueByKeyWithLinq(string key)
{
 return MyDictionary.FirstOrDefault(a => a.Key == key).Value;
}

public string GetValueByKeyWithTryGet(string key)
{
 MyDictionary.TryGetValue(key, out string value);
 return value;
}

public string GetValueByKeyManual(string key)
{
 foreach (var item in MyDictionary)
 {
  if(item.Key == key)
  {
   return item.Value;
  }
 }
 return null;
}

Now we have to add benchmark class. Let’s add “BenchmarkDictionaryLookup.cs”

[MemoryDiagnoser]
[Orderer(BenchmarkDotNet.Order.SummaryOrderPolicy.FastestToSlowest)]
[RankColumn]
public class BenchmarkDictionaryLookup
{
    DictionaryLookup obj = new DictionaryLookup();
        
    [Benchmark(Baseline = true)] // mark this is as baseline method.
    public void GetValueByKey()
    {
      obj.GetValueByKey("test_99"); // i am doing it for worst case by searching the last item.
    }
    [Benchmark]
    public void GetValueByKeyWithLinq()
    {
        obj.GetValueByKeyWithLinq("test_99");
    }
    [Benchmark]
    public void GetValueByKeyWithTryGet()
    {
        obj.GetValueByKeyWithTryGet("test_99");
    }
    [Benchmark]
    public void GetValueByKeyManual()
    {
        obj.GetValueByKeyManual("test_99");
    }
}
class Program
{
    static void Main(string[] args)
    {
       BenchmarkRunner.Run<BenchmarkDictionaryLookup>();
    }
}
dotnet run -p BenchmarkingDemo.csproj -c Release

After benchmarking is completed you will see the following summary result.

Result explanation

Summary

0 comments

answer