The Allocation Trap in Async Hot Paths
While reviewing a high-throughput microservice profiler session, I noticed constant Gen0 garbage collection spikes. Tracing the allocations revealed an unexpected culprit: Task<T> .
When a method is marked async and returns a Task<T> , the C# compiler generates a state machine. Even if your code hits a memory cache and returns a result immediately (synchronously), the runtime still allocates a Task<T> object on the heap to satisfy the method signature.
Before
public async Task < User > GetAsync ( int id ) { if ( _cache . TryGetValue ( id , out var u ) ) return u ; return await _db . QueryAsync ( id ) ; }
Enter fullscreen mode
Exit fullscreen mode
After
public async ValueTask < User > GetAsync ( int id ) { if ( _cache . TryGetValue ( id , out var u ) ) return u ; return await _db .…