Skip to content

Instantly share code, notes, and snippets.

@bellons91
Created January 30, 2024 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bellons91/9ba464941888510c03d384b08caa8d0a to your computer and use it in GitHub Desktop.
Save bellons91/9ba464941888510c03d384b08caa8d0a to your computer and use it in GitHub Desktop.
Performance benchmark of Catch + When vs Catch + If-Else
[MemoryDiagnoser]
public class TryCatchWhenBenchmark
{
[Params(100, 10_000, 100_000)]
public int Size;
[Benchmark]
public void WithIfElse()
{
for (int i = 0; i < Size; i++)
{
try
{
if (i % 3 == 0)
{
throw new ArgumentException(message: "", paramName: "3");
}
else if (i % 5 == 0)
{
throw new ArgumentException(message: "", paramName: "5");
}
}
catch (ArgumentException ex)
{
if (ex.ParamName == "3")
{
string x = "I am 3";
}
else if (ex.ParamName == "5")
{
string x = "I am 5";
}
}
catch
{
string x = "I am other";
}
}
}
[Benchmark]
public void WithWhen()
{
for (int i = 0; i < Size; i++)
{
try
{
if (i % 3 == 0)
{
throw new ArgumentException(message: "", paramName: "3");
}
else if (i % 5 == 0)
{
throw new ArgumentException(message: "", paramName: "5");
}
}
catch (ArgumentException ex) when (ex.ParamName == "3")
{
string x = "I am 3";
}
catch (ArgumentException ex) when (ex.ParamName == "5")
{
string x = "I am 5";
}
catch
{
string x = "I am other";
}
}
}
}

BenchmarkDotNet v0.13.11, Windows 11 (10.0.22621.3007/22H2/2022Update/SunValley2) 13th Gen Intel Core i5-1345U, 1 CPU, 12 logical and 10 physical cores .NET SDK 8.0.101 [Host] : .NET 8.0.1 (8.0.123.58001), X64 RyuJIT AVX2 [AttachedDebugger] DefaultJob : .NET 8.0.1 (8.0.123.58001), X64 RyuJIT AVX2

Method Size Mean Error StdDev Median Gen0 Allocated
WithIfElse 100 147.4 us 4.06 us 11.78 us 140.9 us 1.7090 10.65 KB
WithWhen 100 142.6 us 2.80 us 2.87 us 142.5 us 1.7090 10.65 KB
WithIfElse 10000 14,279.8 us 259.62 us 651.33 us 14,127.6 us 171.8750 1057.47 KB
WithWhen 10000 14,238.5 us 193.59 us 171.61 us 14,236.6 us 171.8750 1057.47 KB
WithIfElse 100000 139,117.7 us 2,769.26 us 5,133.00 us 137,155.6 us 1500.0000 10574.62 KB
WithWhen 100000 142,923.5 us 2,785.94 us 3,316.46 us 142,217.0 us 1500.0000 10573.09 KB
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment