I'm doing a benchmark on Task<T>
and ValueTask<T>
. Source code below:
#LINQPad optimize+ // Enable compiler optimizations
void Main()
{
Util.AutoScrollResults = true;
BenchmarkRunner.Run<TaskAndValueTaskComparsion>();
}
[ShortRunJob]
public class TaskAndValueTaskComparsion
{
[Benchmark]
public ValueTask<int> RunValueTaskWithNew()
{
return new ValueTask<int>(1);
}
[Benchmark]
public Task<int> RunTaskFromResult()
{
return Task.FromResult(1);
}
}
For the result, the Task<T>
is way faster than ValueTask<T>
. But why? I really expected the ValueTask<T>
would cause less allocation when returning task objects.