JIT & AOT
Just-in-time and Native AOT trade-offs.
JIT and AOT Compilation in ASP.NET Core
About This Tutorial
- Difficulty: Intermediate
- Category: .NET Fundamentals
- Prerequisites: Basic C#, .NET SDK and runtime, and basic ASP.NET Core knowledge.
- Learning outcomes: Explain IL, CLR, JIT, Native AOT, trimming, compatibility constraints, publishing, performance trade-offs, and interview concepts.
1. Introduction
C# is a high-level language, while a CPU executes machine instructions. .NET bridges the gap by compiling C# into an intermediate representation and then executing it through a runtime or native code.
- JIT (Just-In-Time): compiles Intermediate Language (IL) into native machine code at runtime as methods are needed.
- AOT (Ahead-of-Time): compiles code into native machine code before the application runs. In modern .NET, Native AOT is a key AOT publishing option.
JIT and AOT are compilation strategies, not web frameworks. ASP.NET Core commonly uses JIT, while supported applications can be published with Native AOT.
Key idea: JIT offers broad runtime flexibility. Native AOT can improve startup and deployment characteristics for suitable applications, but it introduces compatibility and build considerations.
2. From C# to machine code
A typical .NET build compiles C# source into an assembly containing Intermediate Language (IL) and metadata. At runtime, the Common Language Runtime (CLR) loads the assembly. With JIT, methods are compiled to native code as needed. With Native AOT, native compilation occurs during publishing.
| Term | Meaning |
|---|---|
| C# compiler | Converts source code into IL and metadata for a normal managed build |
| IL | Intermediate instructions stored in a .NET assembly |
| Assembly | A .dll or .exe containing code and metadata |
| CLR | Runtime services including garbage collection and managed execution |
| JIT | Converts IL methods into native code at runtime |
| AOT | Compiles code ahead of execution |
| Native AOT | .NET publishing mode that creates a native executable |
| Trimming | Removes code static analysis determines is unused |
| Reflection | Inspects or invokes types and members at runtime |
| Dynamic code | Code generated or compiled during application execution |
3. JIT compilation explained
JIT means Just-In-Time. When a method needs to execute and native code is not available, the runtime can compile its IL into native machine code. The compiled code is generally reused on subsequent calls.
public static int Add(int a, int b)
{
return a + b;
}
A normal build compiles this method to IL. The JIT compiles it for the target machine when needed.
JIT execution flow
- The CLR loads the required assembly.
- The application calls a method.
- If native code is not available, the JIT compiles the method.
- The CPU executes the generated code.
- Later calls can reuse the compiled code.
- Runtime profiling and tiered compilation may further optimize frequently used methods.
Tiered compilation and Dynamic PGO
Modern .NET can use tiered compilation: it may initially compile a method quickly, then recompile frequently used methods with more optimization. Dynamic Profile-Guided Optimization (Dynamic PGO) uses information observed during execution to guide JIT optimizations.
Advantages
- Broad compatibility with .NET libraries and runtime features.
- Runtime optimization can use observed execution behavior.
- Straightforward deployment for many applications.
- No need to resolve every AOT or trimming compatibility issue.
Trade-offs
- Some compilation work occurs during execution.
- First-use latency may be higher for methods not yet compiled.
- Framework-dependent deployments require a compatible shared .NET runtime.
- Runtime compilation consumes CPU and memory.
Note: JIT does not recompile an entire application on every method call. Compiled native code is normally reused.
4. AOT compilation explained
AOT means Ahead-of-Time. The code is compiled before the application runs. In modern .NET, Native AOT produces a native executable for a particular operating system and CPU architecture.
Example:
dotnet publish -c Release -r linux-x64 -p:PublishAot=true
The target runtime identifier must match the deployment platform. Native AOT builds may require platform-specific native toolchains.
Benefits
- Can improve startup by avoiding runtime JIT work for application code.
- May reduce memory usage for suitable workloads.
- Produces a native executable without requiring a separately installed shared .NET runtime.
- Can fit command-line tools, short-lived services, and startup-sensitive APIs.
Trade-offs
- Not every library or runtime feature is compatible.
- Reflection may require metadata preservation or code changes.
- Runtime code generation can be unsupported.
- Trimming can remove code only accessed dynamically if dependencies are not described correctly.
- Builds can require native toolchains and more compatibility analysis.
- Output is platform- and architecture-specific.
- AOT is not guaranteed to produce a smaller file or higher throughput in every application.
Warning: Do not enable Native AOT just because it sounds faster. Verify dependency compatibility and benchmark the published application under realistic load.
5. JIT vs Native AOT
| Factor | JIT | Native AOT |
|---|---|---|
| Compilation timing | Runtime, when methods are needed | Build/publish time |
| Runtime JIT for application code | Yes | No |
| Startup | May incur JIT work | Often faster, workload-dependent |
| Steady-state throughput | Can benefit from tiered JIT and Dynamic PGO | Depends on ahead-of-time compilation and workload |
| Runtime profiling optimizations | Supported by modern JIT | Does not use the same runtime JIT recompilation model |
| Deployment | Framework-dependent or self-contained managed app | Native executable for a target platform |
| Shared runtime | Needed for framework-dependent deployment | Generally not needed separately for application execution |
| Reflection/dynamic code | Broad support | Some patterns require changes or are unsupported |
| Trimming | Optional in some deployment modes | Commonly part of Native AOT publishing |
| Compatibility | Generally broader | Dependency graph must be AOT-compatible |
| Best fit | General-purpose applications | Suitable startup-sensitive or constrained workloads |
Do not assume “AOT is always faster” or “JIT is always slower.” Startup, warmed-up throughput, memory, deployment size, and compatibility are different concerns.
6. Build an ASP.NET Core API
Step 1: Create a project
dotnet new web -n CompilationDemo
cd CompilationDemo
Step 2: Add endpoints
Replace Program.cs with:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello from ASP.NET Core!");
app.MapGet("/sum/{a:int}/{b:int}", (int a, int b) =>
Results.Ok(new
{
FirstNumber = a,
SecondNumber = b,
Sum = a + b
}));
app.Run();
Step 3: Run normally
dotnet run
Use the local URL printed by the application. Test /sum/10/20; the response should contain a sum of 30.
Step 4: Publish a normal Release build
dotnet publish -c Release
This uses the project's default publish behavior and is not necessarily Native AOT.
Step 5: Publish with Native AOT
Add this property inside the existing <PropertyGroup> in CompilationDemo.csproj:
<PublishAot>true</PublishAot>
Then publish for the target platform, for example Linux x64:
dotnet publish -c Release -r linux-x64
Alternatively, pass the property directly:
dotnet publish -c Release -r linux-x64 -p:PublishAot=true
Step 6: Test the published executable
Run the generated executable and verify the endpoints, configuration, logging, and health checks. Test the actual publish output—not only dotnet run.
Benchmark fairly: compare Release builds, the same hardware and workload, cold-start and steady-state behavior separately, and repeat measurements.
7. ASP.NET Core Native AOT considerations
Reflection and trimming
Reflection allows code to inspect types dynamically. Trimming removes code that static analysis believes is unused. If a type or member is discovered only at runtime, the trimmer may not know it must be retained.
Potential risk areas include reflection-based serializers, runtime plugin discovery, object mappers, and libraries that generate code dynamically.
Prefer supported source-generated approaches where suitable, and treat AOT/trimming warnings as actionable diagnostics rather than suppressing them blindly.
Dynamic code
Libraries that use runtime code generation, such as certain Reflection.Emit patterns, may not work with Native AOT. Check dependencies before committing to AOT.
JSON source generation
Source generation can make serialization metadata explicit at compile time:
using System.Text.Json.Serialization;
public sealed record ProductDto(int Id, string Name, decimal Price);
[JsonSerializable(typeof(ProductDto))]
[JsonSerializable(typeof(List<ProductDto>))]
internal partial class ApiJsonContext : JsonSerializerContext
{
}
This declares a source-generation context. To benefit from it, configure the relevant JSON serializer APIs to use ApiJsonContext; declaring the class alone does not change every serialization call automatically.
Compatibility checklist
- Review Native AOT support for the target .NET and ASP.NET Core version.
- Check important dependencies for AOT and trimming compatibility.
- Publish early to discover warnings.
- Fix unsupported patterns or preserve required metadata correctly.
- Test the published executable with integration tests.
- Benchmark startup, memory, throughput, and artifact size.
- Repeat checks after SDK or dependency upgrades.
8. Performance and choosing a model
Measure the metrics that match the application’s needs:
- Startup latency: process launch to readiness.
- First-request latency: duration of the first request.
- Steady-state latency: request latency after warm-up.
- Throughput: requests completed per second.
- Memory: working set and managed heap behavior under load.
- CPU: total usage and compilation/runtime work.
- Publish size: complete deployment artifact size.
- Operational complexity: build requirements and platform coverage.
| Situation | Starting point | Why |
|---|---|---|
| General business API | JIT | Broad compatibility and runtime optimization |
| Small service with strict startup goals | Evaluate Native AOT | Startup may improve |
| Reflection-heavy application with dynamic plugins | Usually JIT initially | Fewer AOT constraints |
| Short-lived serverless process | Evaluate Native AOT | Cold-start costs may matter |
| Dependency requires runtime code generation | JIT unless a supported alternative exists | AOT may not support the pattern |
| High-throughput long-running service | Benchmark compatible options | Steady-state behavior decides |
Benchmarking best practices
- Use Release builds and equivalent features.
- Keep hardware, OS, test data, and dependency versions comparable.
- Separate cold-start tests from warmed-up throughput tests.
- Repeat measurements and record variance.
- Test the actual published artifact.
- Include memory, CPU, deployment size, and compatibility—not just request speed.
9. Common mistakes
- Claiming JIT compiles a method on every call. Compiled code is normally reused.
- Claiming AOT removes every runtime component. Native AOT still uses services such as GC and exception handling.
- Assuming AOT always improves throughput. Measure startup and steady-state behavior separately.
- Assuming AOT always produces a smaller executable. Included code and runtime support affect size.
- Publishing for the wrong runtime identifier. Native output is platform- and architecture-specific.
- Ignoring trimming warnings. Dynamically accessed code may be removed.
- Assuming every NuGet package supports AOT. Verify dependencies.
- Testing only with
dotnet run. Test the actual AOT executable. - Comparing Debug JIT to Release AOT. Keep configurations comparable.
- Suppressing warnings without investigation. Resolve the underlying compatibility issue first.
10. Best practices
- Use JIT as the baseline unless requirements justify evaluating AOT.
- Identify the real priority: startup, throughput, memory, size, or compatibility.
- Measure cold start and steady state separately.
- Publish Native AOT early in development.
- Review analyzer and trimming warnings.
- Verify dependency compatibility before adopting AOT.
- Prefer source-generated metadata where appropriate.
- Keep target runtime identifiers explicit in CI/CD.
- Test the published executable in a production-like environment.
- Re-run benchmarks after SDK or dependency upgrades.
- Record the environment and methodology for reproducibility.
- Avoid selecting AOT based only on a general claim that it is faster.
- Document the team's decision and supporting measurements.
11. Interview questions and answers
Beginner
1. What is JIT in .NET?
JIT means Just-In-Time compilation. The runtime converts IL into native machine code when methods need to execute. Compiled code can generally be reused.
2. What is AOT?
Ahead-of-Time compilation produces native machine code before application execution. Native AOT is a .NET publishing mode that creates a native executable for a target platform.
3. What is the difference between C# and IL?
C# is the source language. IL is an intermediate instruction format produced by a normal .NET build.
4. What is the CLR?
The Common Language Runtime provides managed execution services, including garbage collection and exception handling, and coordinates JIT compilation in a JIT deployment.
5. Does ASP.NET Core use JIT by default?
Typical managed ASP.NET Core applications use the normal .NET execution model, which includes JIT. Supported applications can also be published using Native AOT.
6. Does JIT compile a method on every call?
No. Generated native code is generally reused. Tiered compilation may later generate a more optimized version.
7. What is Native AOT?
A .NET publishing mode that compiles application code ahead of time into a native executable.
8. Is Native AOT cross-platform?
.NET supports multiple Native AOT targets, but each executable is specific to an operating system and architecture. Publish for the correct runtime identifier.
9. What is trimming?
Trimming removes code that static analysis determines is unused. Dynamically accessed members may need explicit preservation or alternative implementation patterns.
10. Is AOT always faster than JIT?
No. AOT can improve startup in suitable workloads, but throughput, memory, and total performance depend on the application and must be measured.
Intermediate
1. Explain the JIT flow.
The compiler emits IL and metadata; the CLR loads the assembly; the JIT compiles a method when needed; native code executes and is normally reused.
2. What is tiered compilation?
It allows quickly compiled code to be replaced by more optimized code for frequently used methods, balancing startup and steady-state performance.
3. What is Dynamic PGO?
It uses observations from actual execution to guide JIT optimizations for hot code paths.
4. Why can Native AOT improve startup?
Application code does not need runtime JIT compilation. Other startup costs remain, so the benefit depends on the workload.
5. Why can Native AOT cause compatibility problems?
Reflection, dynamic code generation, and metadata accessed only at runtime can conflict with static analysis and ahead-of-time compilation.
6. What is the relationship between trimming and Native AOT?
Native AOT publishing uses trimming analysis to remove code it determines is unnecessary. Dynamically accessed code may need explicit preservation.
7. Can Native AOT use reflection?
Some reflection is supported, but reflection that relies on metadata removed by trimming may fail. Follow diagnostics and preserve required metadata or use source-generated alternatives.
8. What does PublishAot do?
<PublishAot>true</PublishAot> enables Native AOT publishing for supported projects. A target runtime identifier and suitable native toolchain may also be required.
9. When should an ASP.NET Core app use JIT?
JIT is a strong default when broad library compatibility and runtime features matter, especially if dependencies are not AOT-compatible.
10. How do you compare performance fairly?
Use equivalent Release builds, the same machine and workload, and actual publish outputs. Measure cold start, first request, steady-state latency, throughput, memory, CPU, and size.
Advanced
1. How can JIT outperform AOT in long-running workloads?
JIT can use runtime profiling and tiered compilation to optimize hot paths based on observed behavior. AOT makes compilation decisions ahead of time. Results remain workload-dependent.
2. Why can AOT suit serverless workloads?
Short-lived processes may spend a large share of their lifetime starting up. Avoiding runtime JIT can help, although initialization and platform overhead remain.
3. What code patterns challenge Native AOT?
Runtime code generation and dynamically discovered metadata can be challenging. Compatibility depends on the exact API and dependency.
4. How does source generation help AOT?
It generates code or metadata at build time, reducing reliance on runtime discovery. System.Text.Json source generation is one example.
5. Does Native AOT eliminate the CLR and GC?
No. It avoids runtime JIT compilation for application code, but runtime services such as garbage collection and exception handling remain.
6. Framework-dependent vs self-contained deployment?
Framework-dependent deployment expects a compatible shared .NET runtime. Self-contained deployment includes required runtime components. Native AOT produces a native executable without requiring a separately installed shared .NET runtime for application execution.
7. Why is a runtime identifier required?
Native machine code targets a specific OS and CPU architecture; a Linux x64 binary is not generally interchangeable with Windows x64 or Linux ARM64.
8. How would you troubleshoot an AOT publish failure?
Read diagnostics, identify the unsupported API or dependency, consult compatibility guidance, fix the pattern or preserve metadata correctly, and test the published executable.
9. Why is executable size insufficient for choosing AOT?
Startup, throughput, memory, compatibility, build complexity, and operations also matter. Measure the complete deployment and application behavior.
10. How would you recommend a compilation strategy?
Start with requirements and a JIT baseline. If startup or deployment constraints justify AOT, verify dependencies, publish a prototype, run integration tests, and compare results under equivalent workloads.
12. Hands-on exercise
Publish and compare JIT and Native AOT
- Create the
CompilationDemoAPI from Section 6. - Run it with
dotnet runand verify the endpoints. - Publish normally with
dotnet publish -c Release. - Add
<PublishAot>true</PublishAot>to the project file. - Publish for the appropriate target, such as
linux-x64orwin-x64. - Run and test the published executable.
- Measure startup, first-request latency, steady-state latency, memory, and output size.
- Repeat tests and record your environment.
- If publishing fails, record the exact warning/error and identify whether it relates to code, a dependency, trimming, or the native toolchain.
Questions: Which mode starts faster? Does the result change after warm-up? What are the artifact sizes? Did AOT report warnings? Which mode would you choose, and what evidence supports your choice?
13. Summary
One-minute revision
JIT compiles IL to native code during execution; Native AOT compiles application code before execution and publishes a native executable. JIT offers broad compatibility and runtime optimization. Native AOT may improve startup and deployment characteristics, but trimming, reflection, dynamic code, and dependency compatibility must be considered. Benchmark the actual application before choosing.
Key takeaways
- Normal .NET builds produce IL and metadata.
- JIT compiles methods to native code at runtime.
- Tiered compilation and Dynamic PGO can optimize hot methods.
- Native AOT compiles ahead of time for a target platform.
- Native AOT still uses runtime services such as garbage collection.
- Trimming can affect code discovered dynamically.
- Startup, throughput, memory, and executable size are separate measurements.
- The right choice depends on requirements and measured results.
14. Cheat sheet
| Need | Remember |
|---|---|
| Typical ASP.NET Core deployment | JIT is a good starting point |
| Reduce runtime JIT work | Evaluate Native AOT |
| Enable Native AOT | Set PublishAot and target a runtime identifier |
| Reflection-heavy dependency | Verify trimming/AOT compatibility |
| Improve JSON AOT compatibility | Consider System.Text.Json source generation |
| Compare performance | Measure cold start, steady state, memory, CPU, throughput, and size |
| Diagnose publish errors | Inspect diagnostics and native toolchain requirements |
| Choose a model | Follow workload measurements, not assumptions |
15. Revision checklist
- I can explain how C# becomes IL and native code.
- I understand the roles of CLR and JIT.
- I can explain tiered compilation and Dynamic PGO.
- I understand Native AOT publishing.
- I know why native output is platform-specific.
- I understand trimming and reflection concerns.
- I know Native AOT still uses runtime services.
- I can publish a small API in both modes.
- I can compare cold-start and steady-state performance.
- I can answer the interview questions in this tutorial.
16. Further reading
Continue with related Dotnet Interview Ready roadmap topics:
- .NET SDK & Runtime — understand tools used to build and run .NET applications.
- CLR (Common Language Runtime) — learn about managed execution services.
- Garbage Collector in .NET — understand managed memory and collection.
- ASP.NET Core Project Structure — understand application organization.
- Configuration and
appsettings.json— learn environment-specific configuration. - Dependency Injection in ASP.NET Core — understand service registration and lifetimes.
Last updated 10/19/2026
Your notes
Sign in to save personal notes on this topic — they'll sync across your devices.
Was this tutorial helpful?
Help us create more free learning resources. Learn more
