📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you write a correct benchmark with BenchmarkDotNet? Show a benchmark that compares two implementations, and explain [MemoryDiagnoser], baselines, [Params], and how you avoid dead-code elimination and other traps that make results meaningless.

Writing trustworthy micro-benchmarks with BenchmarkDotNet on .NET 10: Release builds, warm-up and statistics, MemoryDiagnoser, baselines and ratios, Params, returning results to defeat dead-code elimination, and reading the results table.

Intermediate Coding Intermediate allocations benchmarkdotnet benchmarking jit performance profiling

🎯 Key points

  • Run in Release without a debugger: BenchmarkRunner refuses Debug builds by default
  • BenchmarkDotNet handles warm-up, pilot, many iterations and statistics (mean, error, StdDev, median)
  • [MemoryDiagnoser] adds Allocated per operation and Gen0/1/2 collections
  • Baseline = true gives Ratio and Alloc Ratio columns for a fair comparison
  • [Params] and [GlobalSetup] build realistic inputs from fields outside the measured code
  • Make the work observable (return it, or Consume a sequence) so the JIT cannot eliminate or constant-fold it
  • Quiet machine, compare Error vs Mean, watch StdDev for GC and environment noise
  • A micro-benchmark proves the method got faster, not that the endpoint did: confirm in production

⏱ 30-second answer

BenchmarkDotNet turns a method into a properly measured experiment: it builds a separate Release process, does warm-up and pilot runs so tiered JIT has finished, runs many iterations and reports mean, error and standard deviation.

A correct benchmark:

  • marks one method Baseline = true, so you get a Ratio column;
  • adds [MemoryDiagnoser] for allocated bytes per operation and GC counts;
  • builds inputs in [GlobalSetup] from fields with [Params] for realistic sizes, not constants the JIT can fold;
  • makes the work observable, by returning the result or consuming the sequence, so the JIT can't remove it as dead code.

Then I check that the difference is bigger than the error, on a quiet machine, before believing it. The trade-off: a micro-benchmark proves one method is faster in isolation; it doesn't prove the endpoint is, so I confirm with production numbers.

🗣 Full answer (senior)

How I would answer this in an interview

"I never time code with a Stopwatch in a loop, because it measures the JIT, the first-call costs and whatever else the machine is doing. BenchmarkDotNet does the boring statistics properly. It generates a separate project, builds it in Release, runs it in its own process, does a pilot phase to choose an iteration count, warms up so tiered compilation and Dynamic PGO have settled, then runs enough iterations to report a mean with a confidence interval.

My benchmark class has a few non-negotiables. One method is marked Baseline = true, so I read the Ratio column rather than raw nanoseconds that change from machine to machine. [MemoryDiagnoser] is always on, because on a server allocations often matter more than CPU time: the Allocated column tells me bytes per operation. Inputs come from fields filled in [GlobalSetup] with [Params], so I'm not measuring setup and the JIT can't fold constants, and I test realistic sizes, say 10, 1,000 and 100,000 items, because the winner often changes with size. And the work must be observable: the method returns its result, or consumes the sequence. If the result is thrown away, the JIT is free to drop the computation, and the number you get measures an empty method, not your code. A result that is suspiciously close to zero is the tell.

The mistake I see is treating a benchmark as the end of the job. It proves that method A is faster than method B on that input, on a warm, quiet machine. Whether the endpoint is faster depends on how much of the request that method is, which you learn from a profile before and production metrics after."


The parts of a benchmark

Attribute / API Purpose
[Benchmark(Baseline = true)] The reference; other methods get Ratio and Alloc Ratio
[MemoryDiagnoser] Allocated bytes/op, Gen0/1/2 collections per 1,000 ops
[Params(10, 1_000, 100_000)] Runs every benchmark for each value
[GlobalSetup] / [IterationSetup] Prepare data once / per iteration (use the latter sparingly: it adds noise)
[SimpleJob(RuntimeMoniker.Net10_0)] Pin or compare runtimes
[ShortRunJob] Fewer iterations for quick checks, not for final numbers

Reading the results

Column Meaning What to check
Mean Average time per operation Compare with Error
Error Half of the 99.9% confidence interval If two means differ by less than this, call it a tie
StdDev Spread High = noisy machine, GC effects or thermal throttling
Ratio Mean / baseline mean 0.40 = 2.5× faster
Allocated Bytes per operation Often the real win on servers

Production example

A team rewrote a CSV parser and claimed a 5× speed-up from a Stopwatch test. BenchmarkDotNet showed the old version was being measured on its first, unoptimised (Tier 0) run; the real gain was 1.6× in time but 92% fewer bytes allocated. In production, Gen 0 collections fell from 40/s to 6/s and import p95 dropped by 18%, which was the number the business cared about.

🔍 What the interviewer is checking

Checks that the candidate can produce trustworthy performance evidence rather than misleading timings.

Green flags

  • Knows about warm-up, tiered JIT and Release builds
  • Uses MemoryDiagnoser and a baseline
  • Returns results to avoid dead-code elimination
  • Reads Error before claiming a win, and links back to profiling and production metrics

Red flags

  • Uses Stopwatch in a loop as proof
  • Benchmarks un-materialised LINQ
  • Claims an endpoint is faster because a micro-benchmark is

📚 Learn in depth

1. Why naive timing lies

first call  : JIT Tier 0 compile + type loading + static ctors   (slow, once)
next 30 calls: Tier 0 code, call counting                           (slower than final)
after ~30   : background Tier 1 rejit with Dynamic PGO              (final speed)
any time    : GC pauses, other processes, CPU frequency scaling

A Stopwatch loop mixes all of these. BenchmarkDotNet separates them.

2. What BenchmarkDotNet does

  1. Generates and builds a project per runtime/job in Release, and refuses to run a non-optimised assembly unless you override the validator.
  2. Runs each benchmark in a separate process, so one benchmark's JIT and GC state doesn't leak into another.
  3. Overhead evaluation: measures an empty method and subtracts it.
  4. Pilot: finds how many invocations per iteration give a measurable iteration time.
  5. Warm-up: runs until results stabilise (tiering done).
  6. Workload: runs the actual iterations; removes outliers; computes statistics.

3. Dead-code elimination and constant folding

The JIT optimises benchmark code like any other code. Two optimisations ruin benchmarks:

Dead-code elimination. If a value is computed and never used, and the computation has no side effects, the JIT may remove it:

[Benchmark]
public void Bad() { var x = Math.Sqrt(_value); }   // x unused: may compile to nothing

[Benchmark]
public double Good() => Math.Sqrt(_value);         // returned: BenchmarkDotNet consumes it

Constant folding. If the inputs are compile-time constants, the JIT may compute the answer once while compiling:

[Benchmark]
public double Bad() => Math.Sqrt(16.0);            // can become 'return 4.0'

private double _value = 16.0;                      // a field read at run time
[Benchmark]
public double Good() => Math.Sqrt(_value);

Lazy sequences. return items.Where(f); only measures creating the iterator. Materialise it, or call .Consume(consumer) with BenchmarkDotNet's Consumer.

4. Allocation measurement

[MemoryDiagnoser] uses GC.GetAllocatedBytesForCurrentThread() around the workload (accurate per operation) and reports collections per 1,000 operations. Allocations measured are managed only; native allocations need other tools.

5. Environment noise

Results are only as good as the machine: close browsers and IDEs, plug in laptops (power-saving changes CPU frequency), avoid shared CI agents for final numbers, and compare runs on the same hardware. BenchmarkDotNet prints the environment (CPU, OS, runtime, GC mode) at the top of the report; keep it with the results. A high StdDev or a bimodal distribution warning usually means GC or the environment, not your code.

6. Comparing runtimes and settings

[SimpleJob(RuntimeMoniker.Net90)]
[SimpleJob(RuntimeMoniker.Net10_0, baseline: true)]

This is how you check what upgrading to .NET 10 gives a particular hot path. You can also compare environment variables such as DOTNET_TieredPGO=0 with custom jobs.

7. Limits

  • Micro-benchmarks run with hot caches and a warm branch predictor; production code competes for cache with everything else.
  • They don't show contention, I/O or ThreadPool effects. Use load tests for those.
  • A benchmark of a method that is 2% of request time can only ever save 2%.

Try it yourself

  1. Benchmark string.Join vs StringBuilder vs string.Concat with [Params(3, 100)] and see the winner change.
  2. Write the Bad() and Good() pairs above and compare the numbers.
  3. Benchmark items.Where(...).Select(...) without consuming it, then with .ToList().
  4. Add [SimpleJob(RuntimeMoniker.Net90)] and Net10_0 jobs to an existing benchmark and compare.
  5. Run with --filter *Parse* from the command line and export results with --exporters markdown.

💻 Code

Comparing a LINQ-based and a span-based way to sum the numbers in a comma-separated line, measured properly.

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;

namespace Perf.Benchmarks;

[MemoryDiagnoser]                       // Allocated bytes/op and GC counts
[SimpleJob(RuntimeMoniker.Net10_0)]
public class SumCsvBenchmarks
{
    [Params(10, 1_000)]                  // the winner can change with size
    public int Count { get; set; }

    private string _line = "";

    [GlobalSetup]                        // setup is not measured
    public void Setup() =>
        _line = string.Join(',', Enumerable.Range(1, Count));

    [Benchmark(Baseline = true)]
    public long Linq() =>               // returns its result: no dead-code elimination
        _line.Split(',').Select(long.Parse).Sum();

    [Benchmark]
    public long Span()
    {
        long total = 0;
        foreach (var range in _line.AsSpan().Split(','))   // .NET 9+ MemoryExtensions.Split
        {
            total += long.Parse(_line.AsSpan()[range]);
        }
        return total;
    }
}

public static class Program
{
    // dotnet run -c Release -- --filter *SumCsv*
    public static void Main(string[] args) =>
        BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args);
}

The shape of the output (illustrative; your numbers depend on hardware):

| Method | Count | Mean       | Error     | Ratio | Allocated | Alloc Ratio |
|------- |------ |-----------:|----------:|------:|----------:|------------:|
| Linq   | 10    |   210.0 ns |   2.1 ns  |  1.00 |     656 B |        1.00 |
| Span   | 10    |    74.0 ns |   0.6 ns  |  0.35 |       - |        0.00 |
| Linq   | 1000  | 24,800 ns  | 190 ns    |  1.00 |   56,552 B |        1.00 |
| Span   | 1000  |  9,300 ns  |  70 ns    |  0.38 |       - |        0.00 |

⚠ Common mistakes

  • Mistake: Optimising without measuring, or measuring with a Stopwatch loop. Why it is wrong: You measure JIT tiers, first-call costs and noise. Instead: Use BenchmarkDotNet, and a profile to choose what to benchmark.
  • Mistake: Micro-optimising cold paths because a benchmark looks impressive. Why it is wrong: A 3× win on code that is 0.5% of request time is invisible. Instead: Benchmark only what a profile shows as hot.
  • Mistake: Not returning the result. Why it is wrong: The JIT can remove the work and you measure nothing. Instead: Return the value or consume the sequence.
  • Mistake: Benchmarking an un-materialised LINQ query. Why it is wrong: You only measure building the iterator. Instead: Materialise it or use Consumer.
  • Mistake: Running from Visual Studio with the debugger, or in Debug. Why it is wrong: No optimisations; numbers mean nothing. Instead: dotnet run -c Release without a debugger.
  • Mistake: Ignoring the Error column. Why it is wrong: A 3% difference inside a 5% error is noise. Instead: Treat overlapping intervals as a tie and rerun on a quiet machine.
  • Mistake: Leaving out [MemoryDiagnoser]. Why it is wrong: On servers, allocations drive GC and tail latency even when Mean looks the same. Instead: Always report Allocated.
  • Mistake: Using [IterationSetup] for cheap setup. Why it is wrong: It forces one invocation per iteration and adds noise for fast methods. Instead: Prefer [GlobalSetup].

🏛 Senior insight: trade-offs

I treat a benchmark as evidence in a pull request, not a trophy: the PR shows the profile that made the method worth optimising, the BenchmarkDotNet table with Mean, Error and Allocated, and afterwards the production metric that moved. Teams that keep a small benchmark project in the repo and run it in CI against a baseline catch regressions early, but CI machines are noisy, so I only fail builds on large, repeatable changes (say over 20%) and track the rest as trends.

Measurement When it fits Cost When not to
BenchmarkDotNet Comparing implementations of a hot method Minutes per run Questions about I/O, contention or the whole endpoint
Load test (k6, Azure Load Testing) Endpoint throughput and percentiles Environment and data setup Choosing between two string-parsing approaches
Production metrics The final verdict Needs a release Early design choices

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions proving an allocation reduction with BenchmarkDotNet Why: Checks they can apply benchmarking to a real hot-path optimisation
    How to answer

    First I prove the method is hot: dotnet-counters shows a high allocation rate and an allocation profile points at it. Then I write a BenchmarkDotNet benchmark with [MemoryDiagnoser] so every change shows Mean and Allocated bytes.

    The usual fixes:

    • ReadOnlySpan<char> slicing instead of Substring and Split, which allocate a string per piece.
    • string.Create (or stackalloc plus TryFormat) to build the final string once.
    • ArrayPool<T>.Shared for temporary buffers, returned in finally.
    • Plain loops instead of LINQ and capturing lambdas in tight loops (enumerator and closure allocations).

    The trade-off is readability: span-based code is harder to maintain, so I only do it where the profile and the benchmark justify it.

  2. When: Candidate says a micro-benchmark does not prove the endpoint is faster Why: Checks they have an end-to-end method: goal, measure, bottleneck, change, verify
    How to answer

    I treat performance as an experiment, not a hunch. First I agree a goal as a number: for example p95 under 200 ms at 300 requests a second. Then I measure a baseline with the same tools I'll use to verify: Application Insights for request and dependency timings, dotnet-counters for CPU, GC and ThreadPool, and a repeatable load test.

    Next I find the bottleneck: is time going to CPU, garbage collection, waiting on I/O (database, HTTP) or waiting on locks? Only then do I change one thing, re-run the same measurement and keep the change only if the numbers moved. I stop once the goal is met.

    The trade-off is time: measuring first feels slower, but guessing usually optimises code that wasn't the problem.

↩ Usually asked after

More in Profiling

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me