🚀 Native AOT = Ultra Performance
JIT compilation has overhead. Native AOT compiles ahead-of-time. Fast startup, low memory, native performance.
📝 AOT Setup
# Project file
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<PublishAot>true</PublishAot>
<TrimMode>full</TrimMode>
<EnableAotAnalyzer>true</EnableAotAnalyzer>
</PropertyGroup>
</Project>
# Publish with AOT
dotnet publish -c Release -r win-x64 --self-contained
# Or
dotnet publish -c Release -r linux-x64 --self-contained
# Or
dotnet publish -c Release -r osx-x64 --self-contained
# AOT-specific features
[UnconditionalSuppressMessage]
[DynamicallyAccessedMembers]
# AOT limitations
- No reflection (limited)
- No dynamic code generation
- No System.Reflection.Emit
- Limited dynamic assembly loading
🎯 AOT Optimizations
// Use source generators for JSON
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(User))]
internal partial class SourceGenerationContext : JsonSerializerContext
{
}
// Use with AOT
var user = JsonSerializer.Deserialize(json, SourceGenerationContext.Default.User);
// Avoid reflection in AOT
// Instead use source generators or compile-time code
// Performance benefits
- ~50% faster startup
- ~30% less memory
- ~20% smaller binary
- Native performance
// Use with Docker (smaller images)
FROM mcr.microsoft.com/dotnet/runtime-deps:8.0-alpine
COPY /app/publish /app
WORKDIR /app
ENTRYPOINT ["/app/myapp"]
// AOT with minimal APIs
var builder = WebApplication.CreateSlimBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello AOT!");
app.Run();
// Trimming warnings
// Use [DynamicallyAccessedMembers] for reflection
// Use source generators instead of reflection
💡 AOT Best Practices
- Use source generators for serialization
- Avoid dynamic code generation
- Test with AOT early in development
- Use trim-friendly libraries
- Profile AOT vs JIT performance
“Native AOT delivers ultra performance. Fast startup, low memory. Essential for high-performance .NET apps.”
