Created
March 1, 2015 12:38
-
-
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"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: