2y ago · Feb 19, 2024 1:30 PM
Standard in .NET uses reflection and allocates a new string on the heap every single call.
Generating a zero-allocation extension method at compile time with a Source Generator:
Because is a compile-time string literal, calling returns the interned string constant with **0 heap allocations** and **O(1) switch dispatch**!
CODE
myEnum.ToString()Generating a zero-allocation extension method at compile time with a Source Generator:
CSHARP
// What the Source Generator produces automatically:
public static class PlayerStateExtensions
{
public static string ToStringFast(this PlayerState state) => state switch
{
PlayerState.Idle => nameof(PlayerState.Idle),
PlayerState.Running => nameof(PlayerState.Running),
PlayerState.Jumping => nameof(PlayerState.Jumping),
PlayerState.Dead => nameof(PlayerState.Dead),
_ => state.ToString()
};
}Because
CODE
nameof() CODE
state.ToStringFast()
SourceGenDev · C# Tooling
Metaprogramming with C# 9+ Source Generators and Roslyn Anal...
Metaprogramming with C# 9+ Source Generators and Roslyn Anal...
The following users thanked SourceGenDev for this post: