Created
February 6, 2022 22:53
-
-
Save SteveDunn/2ccc05f32eb3eed4d485a8f84a58f86f to your computer and use it in GitHub Desktop.
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 System; | |
using System.Runtime.CompilerServices; | |
using BenchmarkDotNet.Attributes; | |
namespace benchmarks | |
{ | |
[MemoryDiagnoser] | |
public class ThrowHelperBenchmarks | |
{ | |
// [GlobalSetup] | |
// public void Setup() | |
// { | |
// System.Diagnostics.Debugger.Launch(); | |
// } | |
[Benchmark(Baseline = true)] | |
public int ThrowingInline() | |
{ | |
int exceptionsCaught = 0; | |
int i = 0; | |
FooProcesser1 processor = new FooProcesser1(); | |
for (i = 0; i < 10_000; i++) | |
{ | |
try | |
{ | |
if (i % 2 == 0) processor.ProcessFoo(new Foo {Bar = null}); | |
else | |
{ | |
processor.ProcessFoo(new Foo {Bar = new Bar()}); | |
} | |
} | |
catch (MissingBarException) | |
{ | |
++exceptionsCaught; | |
} | |
} | |
return exceptionsCaught; | |
} | |
[Benchmark] | |
public int ThrowingUsingHelper() | |
{ | |
int exceptionsCaught = 0; | |
int i = 0; | |
FooProcesser2 processor = new FooProcesser2(); | |
for (i = 0; i < 10_000; i++) | |
{ | |
try | |
{ | |
if (i % 2 == 0) processor.ProcessFoo(new Foo {Bar = null}); | |
else | |
{ | |
processor.ProcessFoo(new Foo {Bar = new Bar()}); | |
} | |
} | |
catch (MissingBarException) | |
{ | |
++exceptionsCaught; | |
} | |
} | |
return exceptionsCaught; | |
} | |
} | |
public class FooProcesser1 | |
{ | |
public void ProcessFoo(Foo foo) | |
{ | |
if (foo.Bar is null) throw new MissingBarException(); | |
} | |
} | |
public class FooProcesser2 | |
{ | |
public void ProcessFoo(Foo foo) | |
{ | |
if (foo.Bar is null) ThrowHelper.ThrowMissingBarException(); | |
} | |
} | |
public static class ThrowHelper | |
{ | |
public static void ThrowMissingBarException() => throw CreateMissingBarException(); | |
[MethodImpl(MethodImplOptions.NoInlining)] | |
private static Exception CreateMissingBarException() => new MissingBarException(); | |
} | |
public class MissingBarException : Exception | |
{ | |
} | |
public class Foo | |
{ | |
public Bar Bar { get; set; } | |
} | |
public class Bar | |
{ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment