.NET Inside Out Part 20 – Try doing nothing but decreasing performance

This is the twentieth part of the .NET Inside Out series. For your convenience you can find other parts in the table of contents in Part 1 – Virtual and non-virtual calls in C#

Let’s take this code and see its performance with BenchmarkDotNet:

Results on Windows 7 and .NET Core 4.6 (I know I should provide details of the environment but this is pretty reproducible, feel free to try it out on your own):

So we can see second method is much slower. Why? That’s because of the inlining. Helper with try cannot be inlined as it would break the stacktrace.

Another example comes from Pro .NET Benchmarking:

Results:

Why? Let’s see the machine code:

So we can see that the second implementation uses variables on the stack instead of the registers. That’s why it’s much slower.