Just-In-Time (JIT) Compilation
The JIT compiler transforms Microsoft Intermediate Language (MSIL) into native machine code at runtime. This process optimizes execution based on the current environment, enabling .NET applications to run efficiently on diverse hardware.
How JIT Works
- Method call triggers JIT.
- MSIL is retrieved from the assembly.
- JIT compiles MSIL to native code.
- Native code is cached for subsequent calls.
public int Add(int a, int b) => a + b;
// First call triggers JIT
int result = Add(2,3);
JIT Compilation Modes
| Mode | Description |
|---|---|
RyuJIT | Default x86/x64 JIT in .NET Core/5+ |
LegacyJIT | Older JIT used by .NET Framework |
Tiered Compilation | Initial quick compile, later optimized tier |
Configuring JIT
Adjust JIT behavior via runtime configuration or environment variables.
{
"runtimeOptions": {
"configProperties": {
"System.GC.Server": true,
"System.Runtime.TieredCompilation": false
}
}
}
Performance Tips
- Use
MethodImplOptions.AggressiveInliningfor hot methods. - Prefer structs for small data objects to reduce heap allocations.
- Enable
tiered compilationfor long-running services.