C# 9 Source Generators: Removing Reflection

Reflection is slow. It happens at runtime. Source Generators happen at compile time. This is the biggest performance lever in modern .NET.

Case Study: AutoMapper

AutoMapper historically used reflection/expression trees to map Object A to Object B. This has startup cost. The new generation of mappers (Mapster, Riok.Mapperly) use Source Generators.

[Mapper]
public partial class CarMapper
{
    public partial CarDto CarToDto(Car car);
}

// Compiler Generates:
public partial class CarMapper {
    public partial CarDto CarToDto(Car car) {
        return new CarDto {
            Id = car.Id,
            Make = car.Make
        };
    }
}

The generated code is as fast as hand-written code because it is hand-written code (just written by the compiler). There is zero runtime overhead.


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.