In this lesson, you will learn how to leverage Tiered Compilation and ReadyToRun (R2R) images to minimize the cold-start latency of your containerized .NET applications.
When a .NET application starts in a container, the Just-In-Time (JIT) compiler usually compiles IL code into machine code on the fly. This "warm-up" period is often the primary culprit behind sluggish container startup times. To combat this, we use two powerful strategies: ReadyToRun and Tiered Compilation.
ReadyToRun (R2R)
ReadyToRun is a form of Ahead-of-Time (AOT) compilation. By publishing your app as R2R, the compiler performs the heavy lifting during the build process, generating native machine code and storing it in the assembly. When the container starts, the runtime loads this pre-compiled code immediately, bypassing the expensive initial JIT phase.
To enable this in your project file, simply add the following property:
<PropertyGroup>
<PublishReadyToRun>true</PublishReadyToRun>
</PropertyGroup>
Tiered Compilation
While R2R speeds up initial execution, it doesn't always produce the most highly optimized code. This is where Tiered Compilation comes in. By default, the runtime uses two tiers:
- Tier 0: Quick compilation with minimal optimization to get the app running fast.
- Tier 1: Re-compilation of frequently used code ("hot paths") with heavy optimization.
When using R2R, the runtime uses the pre-compiled code as the Tier 0 implementation, allowing for near-instant startup. As your application runs and identifies hot methods, the runtime performs background re-compilation to generate highly optimized Tier 1 code. This gives you the best of both worlds: rapid container responsiveness and peak long-term execution throughput.
Configuration
In high-scale container environments, you might want to explicitly control this behavior. While the defaults are excellent, ensure you are not disabling Tiered Compilation in your runtimeconfig.json or environment variables, as doing so would force the runtime to use the slower R2R code exclusively without the benefit of the Tier 1 performance optimizations.
Key Takeaway: Combine ReadyToRun to bypass initial JIT overhead with Tiered Compilation to ensure your application reaches peak performance quickly after the container finishes its cold start.