Skip to content

Instantly share code, notes, and snippets.

@nvivo
Created March 1, 2015 12:38
Show Gist options
  • Save nvivo/75b710b621ea2eb2b490 to your computer and use it in GitHub Desktop.
Save nvivo/75b710b621ea2eb2b490 to your computer and use it in GitHub Desktop.
Demonstration that async/await shouldn't cause any noticiable performance hit just because of "async/await"
using System;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
RunTest("Sync", () => DoSomeRealWork());
RunTest("Async", () => DoSomeRealWorkAsync().Wait());
Console.ReadLine();
}
static void RunTest(string desc, Action action)
{
var loopCount = 10;
var globalSw = Stopwatch.StartNew();
for (var i = 0; i < loopCount; i++)
{
var localSw = Stopwatch.StartNew();
action();
localSw.Stop();
Console.WriteLine("{0} - Elapsed: {1} ms", desc, localSw.ElapsedMilliseconds);
}
globalSw.Stop();
Console.WriteLine("{0} - Average: {1} ms", desc, globalSw.ElapsedMilliseconds / loopCount);
Console.WriteLine();
}
static void DoSomeRealWork()
{
// do something that takes some cycles and memory alocations
var sb = new StringBuilder();
for (var i = 0; i < 1000000; i++)
sb.Append("foobar");
}
static async Task DoSomeRealWorkAsync()
{
DoSomeRealWork();
// additionally awaits 10 times for completed tasks
for (var i = 0; i < 10; i++)
await Task.FromResult(0);
}
}
}
@nvivo
Copy link
Author

nvivo commented Mar 1, 2015

Please note that the async version version has all the additional state machine generated code, and additionally awaits for 10 tasks.

These are the results on my machine:

Sync - Elapsed: 30 ms
Sync - Elapsed: 28 ms
Sync - Elapsed: 25 ms
Sync - Elapsed: 32 ms
Sync - Elapsed: 30 ms
Sync - Elapsed: 26 ms
Sync - Elapsed: 24 ms
Sync - Elapsed: 19 ms
Sync - Elapsed: 21 ms
Sync - Elapsed: 21 ms
Sync - Average: 26 ms

Async - Elapsed: 28 ms
Async - Elapsed: 29 ms
Async - Elapsed: 34 ms
Async - Elapsed: 26 ms
Async - Elapsed: 22 ms
Async - Elapsed: 21 ms
Async - Elapsed: 22 ms
Async - Elapsed: 23 ms
Async - Elapsed: 26 ms
Async - Elapsed: 31 ms
Async - Average: 26 ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment