When working with async programming in C#, you’re likely familiar with Task
. But did you know about ValueTask
? It’s a performance optimization for scenarios where the result is often available synchronously.
ValueTask
?Task
allocates an object on the heap, which can lead to unnecessary overhead if the operation completes synchronously.
ValueTask
is a struct, so it avoids heap allocation in such cases.
Example
public async ValueTask<int> CalculateAsync(int input)
{
if (input < 0)
{
// Synchronous path (no heap allocation)
return 0;
}
// Asynchronous path (heap allocation for Task)
await Task.Delay(100);
return input * 2;
}
ValueTask
:When the operation often completes synchronously.
In high-performance scenarios where allocations matter.
Don’t use ValueTask
if the operation is almost always asynchronous. The overhead of handling both paths might outweigh the benefits.