Intermediate 17 min read

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.

TermMeaning
C# compilerConverts source code into IL and metadata for a normal managed build
ILIntermediate instructions stored in a .NET assembly
AssemblyA .dll or .exe containing code and metadata
CLRRuntime services including garbage collection and managed execution
JITConverts IL methods into native code at runtime
AOTCompiles code ahead of execution
Native AOT.NET publishing mode that creates a native executable
TrimmingRemoves code static analysis determines is unused
ReflectionInspects or invokes types and members at runtime
Dynamic codeCode 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

  1. The CLR loads the required assembly.
  2. The application calls a method.
  3. If native code is not available, the JIT compiles the method.
  4. The CPU executes the generated code.
  5. Later calls can reuse the compiled code.
  6. 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

FactorJITNative AOT
Compilation timingRuntime, when methods are neededBuild/publish time
Runtime JIT for application codeYesNo
StartupMay incur JIT workOften faster, workload-dependent
Steady-state throughputCan benefit from tiered JIT and Dynamic PGODepends on ahead-of-time compilation and workload
Runtime profiling optimizationsSupported by modern JITDoes not use the same runtime JIT recompilation model
DeploymentFramework-dependent or self-contained managed appNative executable for a target platform
Shared runtimeNeeded for framework-dependent deploymentGenerally not needed separately for application execution
Reflection/dynamic codeBroad supportSome patterns require changes or are unsupported
TrimmingOptional in some deployment modesCommonly part of Native AOT publishing
CompatibilityGenerally broaderDependency graph must be AOT-compatible
Best fitGeneral-purpose applicationsSuitable 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

  1. Review Native AOT support for the target .NET and ASP.NET Core version.
  2. Check important dependencies for AOT and trimming compatibility.
  3. Publish early to discover warnings.
  4. Fix unsupported patterns or preserve required metadata correctly.
  5. Test the published executable with integration tests.
  6. Benchmark startup, memory, throughput, and artifact size.
  7. 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.
SituationStarting pointWhy
General business APIJITBroad compatibility and runtime optimization
Small service with strict startup goalsEvaluate Native AOTStartup may improve
Reflection-heavy application with dynamic pluginsUsually JIT initiallyFewer AOT constraints
Short-lived serverless processEvaluate Native AOTCold-start costs may matter
Dependency requires runtime code generationJIT unless a supported alternative existsAOT may not support the pattern
High-throughput long-running serviceBenchmark compatible optionsSteady-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

  1. Claiming JIT compiles a method on every call. Compiled code is normally reused.
  2. Claiming AOT removes every runtime component. Native AOT still uses services such as GC and exception handling.
  3. Assuming AOT always improves throughput. Measure startup and steady-state behavior separately.
  4. Assuming AOT always produces a smaller executable. Included code and runtime support affect size.
  5. Publishing for the wrong runtime identifier. Native output is platform- and architecture-specific.
  6. Ignoring trimming warnings. Dynamically accessed code may be removed.
  7. Assuming every NuGet package supports AOT. Verify dependencies.
  8. Testing only with dotnet run. Test the actual AOT executable.
  9. Comparing Debug JIT to Release AOT. Keep configurations comparable.
  10. 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

  1. Create the CompilationDemo API from Section 6.
  2. Run it with dotnet run and verify the endpoints.
  3. Publish normally with dotnet publish -c Release.
  4. Add <PublishAot>true</PublishAot> to the project file.
  5. Publish for the appropriate target, such as linux-x64 or win-x64.
  6. Run and test the published executable.
  7. Measure startup, first-request latency, steady-state latency, memory, and output size.
  8. Repeat tests and record your environment.
  9. 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

NeedRemember
Typical ASP.NET Core deploymentJIT is a good starting point
Reduce runtime JIT workEvaluate Native AOT
Enable Native AOTSet PublishAot and target a runtime identifier
Reflection-heavy dependencyVerify trimming/AOT compatibility
Improve JSON AOT compatibilityConsider System.Text.Json source generation
Compare performanceMeasure cold start, steady state, memory, CPU, throughput, and size
Diagnose publish errorsInspect diagnostics and native toolchain requirements
Choose a modelFollow 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

Make a Donation