Skip to content

Instantly share code, notes, and snippets.

@jahav
Created June 8, 2022 18:42
Show Gist options
  • Save jahav/3b7584b3722ce0e131196f4224fe28be to your computer and use it in GitHub Desktop.
Save jahav/3b7584b3722ce0e131196f4224fe28be to your computer and use it in GitHub Desktop.
A simple benchmark to compare exception errors with error-indicating return values from performance points of view.
public class ReturnValueVsException
{
private readonly int _depth;
private readonly int _result;
public ReturnValueVsException(int depth = 1, int result = -1)
{
_depth = depth;
_result = result;
}
[BenchmarkDotNet.Attributes.Benchmark]
public int ReturnValue() => ErrorReturningMethod(_depth);
public int ErrorReturningMethod(int currentDepth)
{
if (currentDepth == _depth)
{
return _result;
}
var callResult = ErrorReturningMethod(currentDepth + 1);
if (callResult == -1)
{
return -1;
}
return callResult;
}
[BenchmarkDotNet.Attributes.Benchmark]
public int ExceptionValue()
{
try
{
return ExceptionThrowingMethod(_depth);
}
catch (InvalidOperationException)
{
return -1;
}
}
public int ExceptionThrowingMethod(int currentDepth)
{
if (currentDepth == _depth)
{
throw new InvalidOperationException();
}
return ErrorReturningMethod(currentDepth + 1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment