Skip to content

Instantly share code, notes, and snippets.

@jzebedee
Created February 27, 2022 13:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jzebedee/427b69341e293bacc337535eea45401e to your computer and use it in GitHub Desktop.
Save jzebedee/427b69341e293bacc337535eea45401e to your computer and use it in GitHub Desktop.
Throw helper benchmark
using BenchmarkDotNet;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Engines;
using BenchmarkDotNet.Running;
BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run();
[HardwareCounters(HardwareCounter.BranchInstructions, HardwareCounter.BranchMispredictions)]
[SimpleJob(RunStrategy.Throughput)]
public class C {
[Benchmark(Baseline = true)]
public int BenchInline() {
int x = 0;
for(int i = 0; i < 100_000; i++)
{
try {
x += WithInlineException(i % 100_000 == 0 ? null : i);
} catch(ArgumentNullException) { }
}
return x;
}
[Benchmark]
public int BenchThrowHelper() {
int x = 0;
for(int i = 0; i < 100_000; i++)
{
try {
x += WithThrowHelper(i % 100_000 == 0 ? null : i);
} catch(ArgumentNullException) { }
}
return x;
}
public int WithInlineException(int? num)
=> num switch
{
null => throw new ArgumentNullException(nameof(num)),
int n => n
};
public int WithThrowHelper(int? num) {
return num switch {
null => ThrowHelperNullArgument(),
int n => n
};
[System.Diagnostics.CodeAnalysis.DoesNotReturn]
static int ThrowHelperNullArgument() => throw new ArgumentNullException(nameof(num));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment