MethodImplOptions.AggressiveInlining
: Use this option inform the JIT compiler that the method should be inlined.MethodImplOptions.NoInlining
: Use this option to specify that the method should not be inlined.MethodImplOptions.NoOptimization
: Use this option if you do not want the method to be optimized.MethodImplOptions.Synchronized
: Use this option to inform the JIT compiler that the method should be executed by only one thread at a time.
Benchmarking method inlining performance in C#
It goes without saying that you should never deploy an inlined method without first measuring the results. So, let’s do that. We’ll benchmark the performance of a computation with and without inlining.
Consider the following class named Utility
that contains two methods, NoInliningDemo
and AggressiveInliningDemo
. Both of these methods perform the very same computation, which is calculating the square roots of a series of integers. The source code of the two methods is identical. The only difference is how they are executed — one method is inlined, while the other is not.
public static class Utility
{
[MethodImpl(MethodImplOptions.NoInlining)]
public static void NoInliningDemo(int[] arr)
{
for (int i = 0; i
The logic of the two methods is straightforward. They accept an integer array as a parameter and generate the square root of each integer in the array. The square root value is discarded, i.e., it is neither processed nor returned from either of these methods.
The following code snippet shows the MethodPerformanceBenchmark
class that is used to benchmark the performance of the two methods defined in the Utility
class. Note the usage of the Benchmark
attribute. This attribute, when used on a method, indicates that the method should be benchmarked.
[MemoryDiagnoser]
public class MethodPerformanceBenchmark
{
int[] integerArray = { 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 };
int NumberOfItems = 1000;
[Benchmark]
public void NonAggressive_InliningDemo()
{
for (int i = 0; i
To run the benchmark, execute the following statement at the Visual Studio Command Prompt.
dotnet run -p Method_Impl_Example.csproj -c Release
Figure 1 below shows the results.