- case 1:
bool result = await DoAsync();
- case 2:
ValueTask<bool> task = DoAsync();
bool result = task.IsCompleted ? task.Result : await task;
With case 1
and case 2
above,
can anyone say case 2
is better for performance(cpu, memory, etc.)?
Or, is task.IsCompleted
just duplicated and redundant?
To really know for sure, you'd need to measure using a suitable benchmark. However, I would not expect this to have any significant impact, since
await
already does exactly that - albeit viaGetAwaiter()
(which doesn't allocate). It could actually make the truly async scenario worse.Something similar to this optimization is common in library code, but is typically used to avoid the state machine entirely when a result is likely to be synchronous a lot of the time; for example:
The key point here is that the original method is not
async
in this scenario, so we only pay anyasync
overhead in the truly async path (or in the failure case, to standardise the error stack).Here's a
sharplab.io
link that shows what is going on with this optimization; on the right, you can see the optimized version that doesn't useasync
, which comes out as:The
Awaited
method, however is all of: