Menu

1 / 2

ValueTask vs Task Allocation Traps

DEV Community: dotnet·Maayur Dahake·about 15 hours ago
#w63Ahv1T
#devtodotnet#devto#dev#task#async
Reading 0:00
15s threshold

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 .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.