🏠 VisualStudioTutor.com  ·  C# Tutorial Home  ·  C# Lesson 36 of 40
Lesson 36 of 40 Performance Expert ⏱ 35 min

BenchmarkDotNet & Performance Profiling

Measure performance with a repeatable microbenchmark instead of relying on Stopwatch guesses, and use memory diagnostics to see allocation differences.

Part 1: What You Will Learn

Measure performance with a repeatable microbenchmark instead of relying on Stopwatch guesses, and use memory diagnostics to see allocation differences.

  • Create a benchmark class with `[Benchmark]` methods.
  • Choose a baseline implementation.
  • Use `[MemoryDiagnoser]` to measure managed allocations.
  • Run benchmarks in Release mode and interpret results before optimizing.

Project setup: Create a .NET 10 Console App, install `BenchmarkDotNet`, and run the project in Release configuration.

Part 2: Topic-Specific Working Example

The following example is written specifically for this lesson. Create the project described above, enter the code, run it, and then change some values to observe how the feature behaves.

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

BenchmarkRunner.Run<ParsingBenchmarks>();

[MemoryDiagnoser]
public class ParsingBenchmarks
{
    private const string Data = "101,299.90";

    [Benchmark(Baseline = true)]
    public decimal ParseWithSplit()
    {
        string[] parts = Data.Split(',');
        return decimal.Parse(parts[1]);
    }

    [Benchmark]
    public decimal ParseWithSpan()
    {
        ReadOnlySpan<char> span = Data.AsSpan();
        int comma = span.IndexOf(',');

        return decimal.Parse(span[(comma + 1)..]);
    }
}

Part 3: How the Code Works

  • BenchmarkDotNet performs warmup, repeated measurements, statistical analysis, and environment reporting for you.
  • `Baseline = true` makes the Split version the comparison point.
  • `MemoryDiagnoser` reports allocations, making the temporary array and substrings from `Split` visible.
  • A faster microbenchmark does not automatically mean an application is faster; use the Visual Studio Profiler to identify real application hot paths before optimizing.

Part 4: Mini Project & Practice

Mini project: benchmark two ways of checking whether a product code starts with a prefix. Then profile a larger application in Visual Studio and compare profiler evidence with the microbenchmark.

Tip: Type the code yourself in Visual Studio 2026, run it, then deliberately change one part at a time. The goal is to understand the feature rather than simply copy the finished example.

When you are comfortable with this lesson, continue to Lesson 37.

C# in Visual Studio 2026

📘 This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.

View on Amazon Kindle Edition