Skip to content

Instantly share code, notes, and snippets.

@lahma
Created April 26, 2023 07:14
Show Gist options
  • Save lahma/d40e990876e3186df7ff96380ee22cf6 to your computer and use it in GitHub Desktop.
Save lahma/d40e990876e3186df7ff96380ee22cf6 to your computer and use it in GitHub Desktop.
Throw helper performance
BenchmarkDotNet=v0.13.5, OS=Windows 11 (10.0.22621.1555/22H2/2022Update/SunValley2)
12th Gen Intel Core i9-12900H, 1 CPU, 20 logical and 14 physical cores
.NET SDK=7.0.203
  [Host]     : .NET 6.0.16 (6.0.1623.17311), X64 RyuJIT AVX2
  DefaultJob : .NET 6.0.16 (6.0.1623.17311), X64 RyuJIT AVX2

Method Mean Error StdDev
Case_A 2.423 ns 0.0553 ns 0.0490 ns
Case_B 1.727 ns 0.0480 ns 0.0449 ns
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
namespace Benchmarks;
public class ExceptionBenchmark
{
[Benchmark]
public A Case_A()
{
return new A("first", "last");
}
[Benchmark]
public B Case_B()
{
return new B("first", "last");
}
public class A
{
public A(string firstName, string lastName)
{
if (firstName is null)
{
throw new ArgumentNullException(nameof(firstName));
}
if (lastName is null)
{
throw new ArgumentNullException(nameof(lastName));
}
}
}
public class B
{
public B(string firstName, string lastName)
{
if (firstName is null)
{
ThrowArgumentNullException(nameof(firstName));
}
if (lastName is null)
{
ThrowArgumentNullException(nameof(lastName));
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowArgumentNullException(string paramName)
{
throw new ArgumentNullException(paramName);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment