Created
June 8, 2022 18:42
-
-
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.
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
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