Returning Awaited methods vs Tasks
08/12/2018
I have come across this question several times, I thought it might worth a little investigation. Which of the following method runs faster TestAsync or TestDirect, given the Sum method?
public async Task<int> TestAsync(int a, int b) => await Sum(a, b); public Task<int> TestDirect(int a, int b) => Sum(a, b); public Task<int> Sum(int a, int b) => Task.FromResult(a + b);
At first look there is not much difference, but if we look at the performance of them, one executes faster.
At second look we could assume TestDirect must be faster as the compiler 'probably' does not convert it to a state machine. Or is the compiler smart enough to optimize away the state machine in case of TestAsync?