Tutorials C# & .NET 8 Architect Mastery
ValueTask vs Task: Avoiding allocation in hot paths
On this page
ValueTask: High-Perf Async
A Task is a class (Reference Type). Creating a Task object every millisecond creates thousands of heap allocations. ValueTask is a struct that can avoid this cost entirely.
1. When the result is already available
Imagine reading from a cache. 99.9% of the time, the data is in memory (Synchronous). Returning a `Task` would allocate an object on the heap for no reason. Returning a `ValueTask` allocates 0 bytes if the data is already there. It only allocates if it truly needs to perform an asynchronous operation.
2. The Constraints of ValueTask
ValueTask is for "High Frequency" methods. It has strict rules:
- You cannot `await` it twice.
- You cannot call `.GetAwaiter().GetResult()` on it if it's not finished.
- You should not store it in a field.
4. Interview Mastery
Q: "Does ValueTask make code faster?"
Architect Answer: "ValueTask doesn't make 'Inference' faster, it makes 'Garbage Collection' faster. By reducing heap allocations, we reduce the frequency of GC pauses. This improves the **Tail Latency** (p99) of your application, making it feel smoother and more responsive under heavy load."