Skip to content
Tutorials Center
My learning

Topics

Lesson 162 of 182 ยท Advanced C#

Native AOT, Trimming and Startup

Understand Native AOT, IL trimming, ReadyToRun and tiered JIT in .NET: what each does, which C# code breaks (reflection), how to write trim-safe code and when AOT pays off.

A normal .NET program is shipped as IL, a portable instruction set. When you start it, the runtime's JIT compiler (just-in-time) turns each method into machine code the first time it runs. That is flexible and gives excellent peak speed, but it costs something at the start: the runtime has to load, find the right methods and compile them before your code can do real work. For a web server that runs for weeks this does not matter. For a command-line tool that runs for 50 milliseconds, or a serverless function that is started cold for every burst of traffic, it can be most of the total time.

.NET offers several tools to reduce that cost: tiered compilation (on by default), ReadyToRun images, trimming and Native AOT. This lesson explains what each one does, what C# code they break (mostly reflection), and how to write code that works everywhere.

Where the time goes at startup

When Main begins, a lot has already happened, and a lot is about to happen:

  1. The host starts the runtime and loads core assemblies.
  2. Every method you call for the first time must be compiled to machine code (JIT) unless it was precompiled.
  3. Static constructors and static field initializers run when a type is first used.
  4. Libraries do their own start-up work: building a dependency-injection container, reading configuration, scanning assemblies with reflection.

You cannot see JIT work directly, but the runtime counts it. JitInfo.GetCompiledMethodCount reports how many methods the JIT has compiled on this thread. The first call to a method (or the first use of a generic type with new type arguments) causes compilation, and the second call does not.

C# The JIT compiles on first use

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Exact counts depend on the runtime version and settings, so the program prints only the yes/no answers. The idea is what matters: every distinct piece of code that runs for the first time costs compile time.

Tiered compilation

If the JIT spent a lot of effort optimizing every method, start-up would be slow. If it optimized nothing, steady-state speed would be poor. Tiered compilation (the default since .NET Core 3.0) does both, in stages:

  • Tier 0: the first time a method runs, it is compiled very quickly with few optimizations.
  • Tier 1: when a method has been called often enough (about 30 calls, checked on a timer after a short delay), it is recompiled in the background with full optimization.
  • On-stack replacement (.NET 7): a method with a hot loop that is called only once can switch from tier 0 to optimized code in the middle of running.
  • Dynamic PGO (on by default since .NET 8): tier 0 code is lightly instrumented so tier 1 can use real data such as which branch is usually taken, and which concrete type sits behind an interface call.

You rarely tune any of this. It is useful to know when you read a benchmark: a method measured only a few times is running unoptimized tier-0 code, which is why the performance lesson says never to trust a single stopwatch run.

ReadyToRun: precompiled hints

A ReadyToRun (R2R) image contains precompiled machine code alongside the IL. At start-up the runtime uses the precompiled code immediately, skipping most tier-0 JIT work. It is still a normal .NET app: the JIT is still there, and hot methods are still rejitted at tier 1 for peak speed. You enable it at publish time:

XML
<!-- Read-only: set in your .csproj -->
<PropertyGroup>
  <PublishReadyToRun>true</PublishReadyToRun>
</PropertyGroup>
Terminal
# Read-only: run on your machine; you must name a runtime identifier.
dotnet publish -c Release -r linux-x64

The trade-off is a larger file on disk (the code is stored twice) for a faster start. The .NET runtime libraries themselves ship as ReadyToRun, which is why a "hello world" does not take seconds to start.

Trimming: remove what you do not call

A published self-contained app includes the entire framework it needs: tens of megabytes. Trimming (PublishTrimmed) runs a static analysis from your entry point, follows every call it can see, and removes the types and methods that are never reachable. A console app can shrink dramatically.

The analysis is static, and that is exactly the catch. The trimmer can follow Console.WriteLine("x"). It cannot follow code whose target is decided at run time from a string.

C# Trim-hostile versus trim-friendly lookup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Here both versions work, because we run on the full runtime. In a trimmed app, option 1 might return null or throw, since the Greeter class could have been removed. The failure appears only in the published app, which is why teams test the published output.

Trim warnings

You do not have to guess. The compiler ships trim and AOT analyzers. Turn them on and they report every risky call as a warning:

XML
<!-- Read-only: in your library's .csproj -->
<PropertyGroup>
  <IsAotCompatible>true</IsAotCompatible>   <!-- .NET 8: enables the analyzers -->
</PropertyGroup>
TEXT
Read-only: typical warnings in the build output
warning IL2026: Using member 'Json.Serialize<T>(T)' which has
  'RequiresUnreferencedCode' can break functionality when trimming application code.
warning IL3050: Using member 'Expression.Compile()' which has
  'RequiresDynamicCode' can break functionality when AOT compiling.
warning IL2070: 'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicProperties'
  in call to 'Type.GetProperties()'. The parameter 'type' of method 'Dump(Type)' has no matching annotations.

The attributes behind them are plain C# and live in System.Diagnostics.CodeAnalysis:

  • [RequiresUnreferencedCode("reason")] marks a method that only works if nothing was trimmed. Callers get a warning.
  • [RequiresDynamicCode("reason")] marks a method that needs the JIT at run time (for example, emitting IL).
  • [DynamicallyAccessedMembers(...)] on a Type parameter tells the trimmer: "keep the public properties of whatever type is passed here."

The third one is how you make reflection safe: instead of hiding a type behind a string, you let the caller pass typeof(T) and tell the trimmer what you will do with it.

C# Annotating reflection so the trimmer keeps what you use

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

When the trimmer sees Dump(typeof(Point)), it now knows to keep Point's public properties. Without the attribute it would warn (IL2070) that it cannot tell what you do with type.

Native AOT: no JIT at all

Native AOT (ahead-of-time) goes further than ReadyToRun. At publish time the whole program, plus the parts of the framework it uses, is compiled to a native executable for one operating system and CPU. There is no IL to load and no JIT in the process. You enable it with one property:

XML
<!-- Read-only -->
<PropertyGroup>
  <PublishAot>true</PublishAot>
</PropertyGroup>
Terminal
# Read-only: needs the native toolchain (Visual Studio C++ tools on Windows, clang on Linux).
dotnet publish -c Release -r linux-x64

The benefits are real:

  • Very fast start-up, often a few milliseconds: no JIT, no assembly loading.
  • Small memory footprint and a small, self-contained file (a console app can be a few megabytes).
  • No runtime to install on the target machine.

Native AOT was introduced for console apps in .NET 7, and ASP.NET Core minimal APIs support it from .NET 8 (use WebApplication.CreateSlimBuilder for a trimmed-down host). The price is a set of restrictions, because the final program contains only code the compiler found at build time.

What does not work

Feature Why
Assembly.LoadFrom, plugins loaded at run time Nothing can be loaded after publish
System.Reflection.Emit, DynamicMethod Needs the JIT
Expression<T>.Compile() Falls back to a slow interpreter, or warns
Reflection over arbitrary types Metadata for unused members is removed
Generic instantiation not visible at build time Value-type generics need compile-time code
Reflection-based JSON, serializers, mappers, DI scanning Same reason: they find types by inspection

The standard replacement is the source generator you met in the previous lesson. System.Text.Json with [JsonSerializable], GeneratedRegex, LoggerMessage, the configuration binding generator and the ASP.NET Core request-delegate generator all exist so that AOT apps do not need reflection.

Two runtime switches help you write code that adapts. RuntimeFeature.IsDynamicCodeSupported is false under Native AOT, and JsonSerializer.IsReflectionEnabledByDefault is false in trimmed or AOT apps.

C# Writing code that adapts to AOT

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

On the regular runtime, as here, both switches report True. In a Native AOT build, the first becomes False and the code takes the interpreter path.

Choosing between the options

JIT (default) ReadyToRun Trimmed Native AOT
Start-up Slowest Faster Same as JIT Fastest
Peak speed Best (PGO) Best (rejit) Best Good, but usually slightly lower
File size Small (IL) Larger Smaller Small and self-contained
Reflection Full Full Needs annotations Strictly limited
Run-time plugins Yes Yes Yes No

Peak throughput can be lower under Native AOT because there is no tier-1 rejit with real-world profile data, and the compiler targets a baseline CPU instruction set unless you configure more. For long-running servers the JIT is often just as good or better.

Startup is also your own code

Native AOT cannot rescue a program that does a lot of work at start-up. A static field that builds a big table, an eager scan of every type in the assembly, a DI container that validates a thousand registrations: these costs are yours. Two habits help:

  • Do work lazily: Lazy<T> or create things when first needed.
  • Avoid heavy static initializers in types that are touched on every start.

The order in which static initialization happens is also easy to observe.

C# Static initialization runs on first use

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The static constructor runs once, immediately before the first access, and the lazy value runs its factory once. Neither line runs at program start.

When to use what

  • Default JIT with tiered compilation: web servers, long-running services, anything where start-up is a rounding error. Do nothing.
  • ReadyToRun: desktop apps, CLI tools and containers where start-up matters but you still need full .NET features. An easy win with little risk.
  • Trimming: self-contained deployments where size matters. Test the published output and enable the analyzers.
  • Native AOT: command-line tools, serverless functions, sidecar containers, anywhere start-up and memory dominate. Avoid it when you depend on libraries that use heavy reflection or plugin loading (many ORMs and mapping libraries, for instance, have limited or no support) and check each package's AOT support first.

Trim and AOT problems usually appear only in the published app. Always run your tests, or at least a smoke test, against the published output, and treat IL2xxx and IL3xxx warnings as errors in libraries you intend to be AOT-compatible.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main reason a .NET app starts more slowly than a comparable native program?

    Start-up includes runtime initialization, assembly loading and JIT compilation of methods on their first call. ReadyToRun and Native AOT reduce or remove that work.
  2. 2. What does tiered compilation do?

    Tier 0 gives fast start-up with little optimization. Methods that are called often are rejitted at tier 1 with full optimization, optionally guided by dynamic PGO data.
  3. 3. Why is Type.GetType("Greeter") risky in a trimmed app?

    The trimmer follows static references. A type name held in a string is invisible to it, so the class can be removed. typeof(Greeter) is a visible reference.
  4. 4. Which of these generally does NOT work under Native AOT?

    Native AOT produces a closed program. There is no JIT and no IL loader, so run-time loading and Reflection.Emit are unavailable. Source-generated JSON, records and LINQ work.
  5. 5. What does ReadyToRun add compared with a normal publish?

    ReadyToRun images contain precompiled code as a start-up aid. The JIT is still present and rejits hot methods, so peak speed is kept, at the cost of a larger file.

Summary

  • The JIT compiles each method on first use; tiered compilation trades quick start for later optimization, and dynamic PGO improves tier-1 code.
  • ReadyToRun precompiles code for faster start-up while keeping the JIT; trimming removes code that static analysis cannot reach.
  • Native AOT compiles the whole app to a native executable: fastest start, smallest memory, no run-time code generation or loading.
  • Reflection by string, Reflection.Emit, plugins and Expression.Compile are the usual breakers; replace them with source generators, typeof, factory tables and [DynamicallyAccessedMembers].
  • Enable the analyzers (IsAotCompatible), watch for IL2xxx and IL3xxx warnings and test the published output.
  • Start-up cost is also your own code: make expensive work lazy.

Next: Interop, COM and Native Code