Here is the benchmark for the method return task, but synchronize under the hood.
class MainClass { public static async Task<int> UsingAsyncModifier() { return 10; } public static Task<int> UsingTaskCompletionSource() { TaskCompletionSource<int> tcs = new TaskCompletionSource<int>(); tcs.SetResult(10); return tcs.Task; } public static Task<int> UsingTaskFromResult() { return Task.FromResult(10); } public static void Main(string[] args) { DateTime t = DateTime.Now; const int repeat = 10000;
Exit (repeat 10,000 / 100,000 / 1,000,000 times):
Repeat 10000 times. UsingAsyncModifier: 00:00:00.1043980 UsingTaskCompletionSource: 00:00:00.0095270 UsingTaskFromResult: 00:00:00.0089460
Repeat 10,000 times using TaskFromResult 10 times faster than UsingAsyncModifier.
Repeat 100000 times. UsingAsyncModifier: 00:00:00.1676000 UsingTaskCompletionSource: 00:00:00.0872020 UsingTaskFromResult: 00:00:00.0870180
Repeat 100,000 times using UseTaskFromResult 2x faster than UsingAsyncModifier.
Repeat 1000000 times. UsingAsyncModifier: 00:00:00.8458490 UsingTaskCompletionSource: 00:00:00.8870980 UsingTaskFromResult: 00:00:00.9027320
Repeat 1,000,000 times, UsingAsyncModifier is a little faster than UseTaskFromResult.
I think the async modifier has just created a completed task, something like Task.FromResult() . But this checkpoint does not prove my idea. Why?
source share