Thursday, July 4, 2013

Overhead of using async and await in C# 4.5

Although asynchronous code is touted as allowing for more scalable architectures through less threads (a la nodejs), there must be a latency overhead to this technology. While the total throughput of the system may be higher, an individual request must be slowed down due to increased context switching.

I was interested in seeing how much of a performance impact there is to using the new Async pattern in .NET (and simplified using the fantastic async / await keywords in C#).

I wrote an application that compares the FileStream.Read and FileStream.ReadAsync calls in a tight loop, reading one byte into a byte array 1 million times. Tweaking the file size and other parameters resulted in very different results, although the synchronous call was always at least five times faster than the asynchronous call.

Results

File length: 1000000 bytes.
Running 100 loops of Preload...
Done in 0 ms.
Running 1000000 loops of Asynchronous...
Done in 2452 ms.
Running 1000000 loops of Synchronous...
Done in 17 ms.

Conclusion:

In this single test scenario, using this particular method of file access, the overhead of using asynchronous calls for very fast operations is significant in that an operation that takes around 20 ms synchronously runs at 2500 ms asynchronously (125 times slower). In practice, this is an overhead of 0.00000248 seconds (2.5 μs) per asynchronous call. Whether this overhead is acceptable, and whether the reduction in system resources that asynchronous calls are supposed to yield is worth this slowdown is application dependent.

Source code

0 comments:

Post a Comment