This question is not about the cost of throwing exceptions in .NET. In some experiments a while back I saw a significant change in a method performance if it contained a throw statement somewhere in one of the execution paths, without actually ever using it. Does JIT somehow wraps any method that potentially could throw an exception in some extra code?
Share
Yes, there’s a difference. The x86 and x64 jitter optimizers will never inline a method that has a throw statement. The difference is hard to quantify because additional optimizations are possible after it got inlined, but typically a couple of nanoseconds per call.
An optimization strategy used commonly in the .NET framework code is to put the statements that throw the exception in a helper method so that the common code path is still inlined. Visible in the Math.Abs() method for example:
Which ensures that the Abs() method itself is inlined and only negative values take the non-optimal code path.