Skip to content

Instantly share code, notes, and snippets.

@SteveDunn
Created February 6, 2022 22:53
Show Gist options
  • Save SteveDunn/2ccc05f32eb3eed4d485a8f84a58f86f to your computer and use it in GitHub Desktop.
Save SteveDunn/2ccc05f32eb3eed4d485a8f84a58f86f to your computer and use it in GitHub Desktop.
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