JavaRush /Courses /C# SELF /Performance optimization: ValueTask

Performance optimization: ValueTask

C# SELF
Level 62, Lesson 2
Available

1. Introduction

Before diving into code, let's make it simple. Remember that creating an object in .NET (and especially a task!) costs memory and a bit of CPU time? Now imagine an async API that in half the cases returns the result instantly (for example, gets it from a cache), and in the other half calls the database so the operation becomes truly asynchronous and returns a Task. This is common — for example in file caches, network APIs, object pools and other "async, but sometimes instant" scenarios.

If we always return a Task, even for instant results we'll have to create unnecessary objects. What if we could return the result without a task when it's already ready? That's why ValueTask was born.

Fact: the standard Task.CompletedTask and Task.FromResult(…) do save runtime, but they create shared objects that might not be ideal for high-throughput scenarios.

What is ValueTask

ValueTask is a special wrapper struct that can represent either an already-completed result or (if the operation is actually asynchronous) the task itself. Simply put, it's a "package" that can contain either a plain result or a reference to a Task.

There are two main variants:

  • ValueTask — the "void-ish" one (doesn't return a value, like Task)
  • ValueTask<TResult> — a wrapper for a value (analogous to Task<TResult>)

Comparing Task and ValueTask

Type Number of allocations Can complete synchronously Typical use
Task
One (heap) Yes/No Almost always
ValueTask
Zero/one Yes/No Optimization
ValueTask<T>
Zero/one Yes/No Optimization

When to use ValueTask

There's a golden rule: if you're writing a regular async method that always returns a result only after an async operation, use Task. It's simple, safe and everybody understands it.

Use ValueTask when:

  • The result can be obtained synchronously (for example, from a cache, pool, memory), and you want to save on extra allocations.
  • The asynchronous operation happens infrequently (otherwise the benefits are lost against the added code complexity and struct copying).

Warning! If you always return an asynchronous result — confidently use Task. If you want your API to be "super-optimized" for frequently instant results — then ValueTask.

2. Synchronous or asynchronous result

Consider a function that finds a user by name. If the user is in the cache — we return them instantly; if not — we load them asynchronously from the "database":


// Modeling our user
public class User
{
    public string Name { get; set; }
}

// Our cache (very simple)
private readonly Dictionary<string, User> _localCache = new();

public async ValueTask<User> FindUserAsync(string name)
{
    // Check the local cache
    if (_localCache.TryGetValue(name, out var user))
    {
        // Result is instant — no task allocation!
        return user;
    }

    // Here is supposedly a long async operation (for example, from DB)
    user = await LoadUserFromDbAsync(name);
    // Put into cache for the future
    _localCache[name] = user;
    return user;
}

private async Task<User> LoadUserFromDbAsync(string name)
{
    // Simulate delay
    await Task.Delay(500);
    return new User { Name = name };
}

Important: On a cache hit we return a plain result — no task allocation! Only when the result has to be "fetched" do we actually create an asynchronous task.

How ValueTask is built internally

A ValueTask can hold either a ready value or a reference to a Task:

ValueTask result = ValueTask.CompletedTask;
ValueTask<int> valueResult = new ValueTask<int>(42);
ValueTask<int> valueResult2 = new ValueTask<int>(Task.Run(() => 42));

When you use await the compiler figures it out: if the result is instant, no extra objects will be created.

Important about await and ValueTask

async methods work fine with await for ValueTask:

public async ValueTask PingAsync()
{
    // ...
    await Task.Delay(10);
}

But if you store a ValueTask instance and decide to await it later, remember: you must not await the same instance more than once. Task can be awaited multiple times, ValueTask cannot.

Error: Re-awaiting a ValueTask

ValueTask<int> task = ComputeAsync();

// This is OK
int a = await task;

// This is an error! Second await on the same ValueTask instance is not allowed:
// int b = await task; // DON'T DO THIS!

3. Rewriting part of our console app

Let's say we're developing a mini book reader: some texts are already cached, the rest is fetched asynchronously. We'll implement an optimized method to get the first line of a book using ValueTask:

private readonly Dictionary<string, string> _bookCache = new();

public async ValueTask<string> GetFirstLineOfBookAsync(string title)
{
    if (_bookCache.TryGetValue(title, out var bookText))
    {
        var firstLine = bookText.Split('\n')[0];
        return firstLine;
    }

    // Assume async download of the book
    var downloadedBook = await DownloadBookTextAsync(title);
    _bookCache[title] = downloadedBook;
    return downloadedBook.Split('\n')[0];
}

private async Task<string> DownloadBookTextAsync(string title)
{
    // Simulate delay (for example, downloading from the internet)
    await Task.Delay(1000);
    return $"Book: {title}\nThis is the first line.\nSecond line...";
}

That's how ValueTask saves creating a task when the book is already in the cache.

4. Helpful nuances

Marker: when not to use ValueTask

If your API is always async (for example, always involves network), use Task; it's simpler and safer.

How to convert ValueTask to Task and back

Sometimes ValueTask doesn't fit the API that expects a Task. Use .AsTask():

ValueTask<int> valueTask = ComputeAsync();
Task<int> task = valueTask.AsTask();

If you need to turn a Task into a ValueTask — just create a ValueTask from the task:

Task<int> task = ComputeAsyncTask();
ValueTask<int> valueTask = new ValueTask<int>(task);

Comparison: ValueTask vs Task

Characteristic
Task
ValueTask
Re-await Allowed Not allowed
Allocations on fast responses There are None (if the result is instant)
Compatibility surface Widely supported Requires extra wrappers
Applicability Everywhere Only for optimization
Pooling Uses shared pool No, it's a struct
Simplicity Simple More complex

Using ValueTask in real life

public async ValueTask<string> GetMessageAsync(int id)
{
    if (_messageCache.TryGetValue(id, out var value))
        return value;

    var result = await LoadMessageFromDbAsync(id);
    _messageCache[id] = result;
    return result;
}

Interview tip: If you're asked how to further boost performance of an async API with caching, mention ValueTask.

Examples of compatibility with LINQ and IAsyncEnumerable<T>

If you want to use ValueTask with async LINQ (IAsyncEnumerable<T>), it's supported in .NET (for example, the ToListAsync method):

public async ValueTask<List<int>> GetPrimeNumbersAsync()
{
    // Simulate that part of numbers are already computed, part are async
    // ... (example omitted for brevity)
    return new List<int> { 2, 3, 5, 7, 11 };
}

5. Conclusions and implementation notes

  1. Use ValueTask for optimization when a significant portion of the time your result is ready instantly (for example, from a cache).
  2. Don't use ValueTask "just because" — it will complicate code and cause bugs.
  3. Don't await a ValueTask multiple times. If you need to — convert it to a Task.
  4. All compatibility logic with Task is via .AsTask().
  5. Remember that ValueTask is a struct, and it can behave differently when copied.

6. Common mistakes when working with ValueTask

Mistake #1: re-awaiting the same ValueTask instance. ValueTask is a struct; you can't await it twice. A second await will throw or behave incorrectly.

Mistake #2: using ValueTask without checking compatibility. Some third-party APIs expect a Task, and passing a ValueTask directly can cause issues.

Mistake #3: using ValueTask without need. If the result is always asynchronous, using ValueTask complicates code without real benefit.

Mistake #4: copying ValueTask as a struct. A copied struct can behave unexpectedly when awaited; work with the original carefully.

2
Task
C# SELF, level 62, lesson 2
Locked
Return the result instantly or asynchronously
Return the result instantly or asynchronously
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION