Revisit Try Catch Overhead
During a lunch break, a colleague said there is no try-catch overhead in C# if there is no exception thrown, this surprised me. From what I understand in C++, overhead is always there for try-catch setup, even though no exception is thrown, the language does not know if it will throw.
Let's do a weekend small project to find this out with a nice bench mark library [benchmarkdotnet](https://benchmarkdotnet.org/articles/guides/getting-started.html "benchmarkdotnet")
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
var summary = BenchmarkRunner.Run<TryCatchOverHead>();
public class TryCatchOverHead
{
[Benchmark]
public int NotTryCatch()
{
var a = 1;
var b = 2;
var result = a / b;
return result;
}
[Benchmark]
public int NotExceptionThrow()
{
try
{
var a = 1;
var b = 2;
var result = a / b;
return result;
}
catch (Exception ex)
{
return 0;
}
}
[Benchmark]
public int ExceptionThrow()
{
try
{
var a = 1;
var b = 0;
var result = a / b;
return result;
}
catch (Exception ex)
{
return 0;
}
}
}
The output, No try-catch is about 20 times faster than try catch block, with 0.014ns vs 0.274ns
Does it matter? As an engineer, we should know the purpose of try-catch. It is used to deal with exceptions and continue the work, not fatal handling without a reason.
// * Summary *
BenchmarkDotNet v0.13.6, Windows 10 (10.0.19045.3208/22H2/2022Update)
Intel Core i5-4590 CPU 3.30GHz (Haswell), 1 CPU, 4 logical and 4 physical cores
.NET SDK 7.0.100
[Host] : .NET 7.0.0 (7.0.22.51805), X64 RyuJIT AVX2
DefaultJob : .NET 7.0.0 (7.0.22.51805), X64 RyuJIT AVX2
| Method | Mean | Error | StdDev |
|------------------ |--------------:|-----------:|-----------:|
| NotTryCatch | 0.0141 ns | 0.0130 ns | 0.0121 ns |
| NotExceptionThrow | 0.2744 ns | 0.0063 ns | 0.0053 ns |
| ExceptionThrow | 7,624.9444 ns | 66.1726 ns | 58.6603 ns |
// * Warnings *
ZeroMeasurement
TryCatchOverHead.NotTryCatch: Default -> The method duration is indistinguishable from the empty method duration
// * Hints *
Outliers
TryCatchOverHead.NotExceptionThrow: Default -> 2 outliers were removed (2.15 ns, 2.15 ns)
TryCatchOverHead.ExceptionThrow: Default -> 1 outlier was removed (7.82 us)
// * Legends *
Mean : Arithmetic mean of all measurements
Error : Half of 99.9% confidence interval
StdDev : Standard deviation of all measurements
1 ns : 1 Nanosecond (0.000000001 sec)
// ***** BenchmarkRunner: End *****
Run time: 00:01:00 (60.65 sec), executed benchmarks: 3
Global total time: 00:01:05 (65.36 sec), executed benchmarks: 3
// * Artifacts cleanup *
Artifacts cleanup is finished