What is the cost of async/await?
.NET 4.5 (C# 5) had brought the new async/await syntax.
I will cover async/await syntax in more details in future post, but in the meanwhile in case that you are not yet familiar with this syntax, what’s you should have to know is that the syntactic compiler transform that syntax (and the lines that follow the await keyword) into IL, the generated IL is following the concept of the TPL ContinueWith.
the syntactic compiler is actually generating fair amount of IL which represent a state-machine of the async execution.
we do gain lot of benefit from the new async/await syntax (in terms of readability and more) but as I said I will discuss this aspect on latter posts.
the questions which this post is trying to answer is:
- How match do we pay for it?
- Does the compiler is smart enough to minimize the overhead involve with this feature?
the answer for the question is: not only that the compiler is smart enough to mitigate the cost,
it is actually (in most cases) doing better job compare with direct using of ContinueWith.
I have extend Joseph E. Hoag’s benchmark, and I have find consistence improvement of the async/await over the ContinueWith, both in terms of performance and memory allocation.
the benchmarks is targeting both:
real task execution:
and conceptual task execution:
and I was testing the following scenarios:
1. Continuation/Unwarp on both real and conceptual task.
2. await against real and conceptual.
3. then I was testing the Task.FromResult for ContinueWith and await.
4. to make sure that it isn’t the Unwarp thing which is causing the overhead I added the following benchmark.h
all result come in favor of the async/await syntax,
while everything was running under .NET 4.5.
the execution result for 100000 iterations, under virtual machine with 2 cores and 2G of RAM were:
not only async\await doesn’t come with overhead, it is actually perform much better in terms of speed and memory allocation.
It seem that we have benefit both from simplicity and efficiency.