-
-
Save jzebedee/427b69341e293bacc337535eea45401e to your computer and use it in GitHub Desktop.
Throw helper benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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