Monday 18 November 2019

Benchmarking in DotNet to analyse memory footprint

BenchmarkDotNet is a performance measurement tools which generate various console data like
Avg execution time, memory allocation, memory distribution and more for executed methods.


  • It have features to export result in various format.
  • It works with release mode only.
  • Support with console App only, Doesn't support with unit test.
Official Documentation, Youtube Demo


Example:
Let's suppose that we want to explore performance of string replace for both String.Replace & Regex.Replace function. We have prepared dummy csv data by running a loop from 1 - 10000. And created 2 diff functions StringReplace() and RegexReplace() in class StringReplaceVsRegexReplaceBenchmark. We have added vital attributes which BenchmarkDotNet understand. We have chosen Release mode and pressed Ctrl + F5 (Start without debugging).

With given full code snippet, output could be found over console.

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
using System.Collections;
using System.Linq;
using System.Text.RegularExpressions;
 
namespace ReplaceVsRegex
{
    [MemoryDiagnoser]
    [RPlotExporterRankColumn]
    public class StringReplaceVsRegexReplaceBenchmark {
        
        private string data;
        
        [GlobalSetup]
        public void Setup()
        {
            data = string.Join(""Enumerable.Range(1, 10000));
        }
 
        [Benchmark]
        public void StringReplace() =>
            data.Replace("1""x");
 
        [Benchmark]
        public void RegexReplace() =>
            Regex.Replace( data, "1""x");
    }
 
    public class Program
    {
        public static void Main(string[] args)
        {
            var summary = BenchmarkRunner.Run<StringReplaceVsRegexReplaceBenchmark>();
        }
    }
}
  
Output: