如果 ValueTask 依赖于 returns Task 的方法,它仍然有用吗?

Will ValueTask still be beneficial if it depends on a method that returns Task?

以以下方法为例:

public async ValueTask<int> MyMethod() {
    return await GetMyIntegerWithTask();
}

public async Task<int> GetMyIntegerWithTask() {
   if (/*in hot path*/) {
      return await SynchronousMethodThatUsesTask();
   } 
   return await AsynchronousMethodThatUsesTask();
}

public Task<int> SynchronousMethodThatUsesTask() {
   int value = new Random().Next();
   return Task.FromResult(value); 
}

public async Task<int> AsynchronousMethodThatUsesTask() {
   //some asynchronous calculation 
}

使用 ValueTask 作为 MyMethod 的 return 类型是否仍然具有与 ValueTask 相关的优势,因为我希望大部分时间我的代码将同步执行(即使同步方法我依赖于 returns Task 而不是 ValueTask)?

Does using ValueTask as the return type of MyMethod still have the advantages associated with ValueTask because I expect that most of the time my code will execute synchronously (even though the synchronous method I'm depending on returns Task rather than ValueTask)?

ValueTask 的性能优势很小,除非您经常调用它。也就是说,是的,ValueTask 至少会避免 Task 分配,并且在同步情况下也会避免将状态机结构装箱到堆上。

如果 GetMyIntegerWithTaskSynchronousMethodThatUsesTask 也使用 ValueTask<int> 更好 ,但即使没有 MyMethod 也可以使用 ValueTask<int> 至少可以避免 一些 分配。