Minimal API Performance: Source Generators vs Reflection
Benchmarking .NET Minimal APIs with source-generated JSON serialization — 3x throughput improvement with less allocation.
.NET 8’s source generators for JSON serialization eliminate reflection at runtime. I wanted to know if it mattered for our gateway’s hot path.
Benchmark Setup
[MemoryDiagnoser]
public class SerializationBenchmark
{
private readonly Order _order = OrderFactory.CreateLarge();
[Benchmark(Baseline = true)]
public string ReflectionSerialize() =>
JsonSerializer.Serialize(_order);
[Benchmark]
public string SourceGenSerialize() =>
JsonSerializer.Serialize(_order, OrderContext.Default.Order);
}
Results
| Method | Mean | Allocated |
|---|---|---|
| Reflection | 842 μs | 48.2 KB |
| Source Gen | 267 μs | 12.1 KB |
3.2x faster, 75% less allocation.
When It Matters
- High-throughput APIs (>1K req/s per instance)
- Large or nested DTOs
- Latency-sensitive paths
When It Doesn’t
- Low-traffic internal APIs
- Prototyping / MVPs
- DTOs that change frequently (source gen adds compile-time coupling)
We adopted source generators for all gateway request/response models. Compile time increased ~2 seconds — negligible.
performance , dotnet , benchmarks · .NET , C#