Interview frequency: …
Short answer
Create a separate Console project and mark methods with [Benchmark]; the library automatically warms up, isolates the processor, and measures time and memory allocations with [MemoryDiagnoser].
Explanation
Manual Stopwatch measurements can be misleading because of JIT compilation, GC pauses, and processor-frequency changes. BenchmarkDotNet isolates the runtime environment, runs repeated Warmup cycles until code reaches full optimization (Tier 1 JIT), performs hundreds of statistical iterations, and generates precise tables of nanoseconds and Heap allocation bytes.
Code example
[MemoryDiagnoser]
public class StringBenchmarks {
[Benchmark]
public string UsingStringBuilder() {
var sb = new StringBuilder();
for (int i = 0; i < 100; i++) sb.Append(i);
return sb.ToString();
}
}Common mistakes
- Running benchmarks in Debug instead of Release, producing distorted results without compiler optimizations.
Follow-up questions
- What is Method Inlining, and when should you use [MethodImpl(MethodImplOptions.AggressiveInlining)]?