I see more and more open source libraries using .NET 5's Source Generators which improves their performance.
As much as I can understand from the docs, they are meant to replace System.Reflection
becomes it comes at the expense of performance. Is that true? What I personally know about source generators is that when they introduced them in .NET 5, they were meant to generate C# code based on the .proto data contract files.
There is a clone library of MediatR which uses Source Generators instead of System.Reflection
.
Could you simplify the source generators benefits and usage in that MediatR library and overall?
Source generators are really nothing magic - it's just some custom piece of code that generates text into files, which then get inserted into the compilation process and becomes part of the binary output (e.g. DLL or EXE) as if it was manually typed in by hand in some source file before you hit compile.
The only "magic" here is the formalized concept of analyzers-as-generators, which enables Visual Studio to automatically pass in the original source code into your custom generator routine and include the output whenever you build your project.
One application of source generators is to create specialized, type-specific code for some operation that otherwise would require run-time reflection. Run-time reflection is typically rather slow and CPU intensive, yet often needed in order to centralize logic for common operations on unknown objects. A common example is the serialization and deserialization of objects. This could be done either through reflection (lookup properties at run-time, invoke the getters and setters, etc) or through faster, type specific code that directly references properties and reads/writes to and from data streams. However, creating such specialized code for every type is a lot of boring, repetitive work and so - enter source generators. They can do the "reflection" during build time and output slim, fast code into temporary .cs files, which get compiled with the product.