Boosting C# Performance with [MethodImpl(AggressiveInlining)]
When writing high-performance applications in C#, every millisecond counts. One lesser-known yet powerful tool is the [MethodImpl(MethodImplOptions.AggressiveInlining)]
attribute.
In this article, we’ll explore what inlining is, why it matters, and how to use [MethodImpl]
effectively in your .NET applications.
What is Inlining?
Inlining is an optimization performed by the JIT (Just-In-Time) compiler.
Instead of calling a method through a normal function call, the JIT replaces the call site with the actual method body.
int result = Add(3, 5); // Without inlining int result = 3 + 5; // With inlining
Inlining removes method call overhead and sometimes allows the JIT to apply further optimizations.
Forcing Inlining with [MethodImpl]
By default, JIT decides whether to inline a method.
Sometimes, we want to force the JIT to inline. Use [MethodImpl]
:
using System.Runtime.CompilerServices; public class Calculator { [MethodImpl(MethodImplOptions.AggressiveInlining)] public int Add(int a, int b) => a + b; }
This instructs the JIT:
"Please inline this method whenever possible."
Other Useful MethodImplOptions
MethodImplAttribute
offers several options:
Option | Description |
---|---|
AggressiveInlining | Suggests inlining of the method |
NoInlining | Prevents inlining |
NoOptimization | Disables JIT optimizations (good for debugging) |
Synchronized | Adds implicit lock around the method |
InternalCall | Method implemented by CLR internally |
ForwardRef | Implementation is supplied elsewhere (interop) |
When to Use Aggressive Inlining?
Inlining is not a silver bullet. Use it wisely:
Good use cases:
- Small, frequently called methods (
Add
,Multiply
,IsNullOrEmpty
) - Performance-sensitive code (game loops, real-time calculations)
- Utility functions used millions of times
Avoid when:
- Method is large (increases binary size)
- Method is rarely called
- Overuse may hurt CPU cache efficiency
Example: Math Utility
public static class MathUtils { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Square(int value) => value * value; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Cube(int value) => value * value * value; }
Small, frequently used methods are perfect candidates for inlining.
Conclusion
-
[MethodImpl(MethodImplOptions.AggressiveInlining)]
gives you control over JIT optimizations. - Use it on small, performance-critical methods.
- Avoid overuse, as excessive inlining can negatively affect performance.
Sample Code
Check out a simple project demonstrating [MethodImpl]
usage with benchmarks:
GitHub Repository
Tags
#csharp
#dotnet
#performance
#jit
#clr
#softwaredevelopment
I’m Morteza Jangjoo and “Explaining things I wish someone had explained to me”
Top comments (0)