-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathValueTaskOverheadBenchmarks.cs
More file actions
108 lines (84 loc) · 2.98 KB
/
ValueTaskOverheadBenchmarks.cs
File metadata and controls
108 lines (84 loc) · 2.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
namespace StateOfTheDotNetPerformance
{
[MemoryDiagnoser]
public class ValueTaskOverheadBenchmarks
{
[Params(100, 1000)]
public int Repeats { get; set; }
[Benchmark]
public Task<int> ConsumeTask() => ConsumeTask(Repeats);
[Benchmark]
public ValueTask<int> ConsumeValueTaskWrong() => ConsumeWrong(Repeats);
[Benchmark(Baseline = true)]
public ValueTask<int> ConsumeValueTaskProperly() => ConsumeProperly(Repeats);
[Benchmark]
public ValueTask<int> ConsumeValueTaskCrazy() => ConsumeCrazy(Repeats);
async Task<int> ConsumeTask(int repeats)
{
int total = 0;
while (repeats-- > 0)
total += await SampleUsageAsync();
return total;
}
Task<int> SampleUsageAsync() => Task.FromResult(1);
async ValueTask<int> ConsumeWrong(int repeats)
{
int total = 0;
while (repeats-- > 0)
total += await SampleUsage();
return total;
}
async ValueTask<int> ConsumeProperly(int repeats)
{
int total = 0;
while (repeats-- > 0)
{
ValueTask<int> valueTask = SampleUsage(); // INLINEABLE
total += valueTask.IsCompleted
? valueTask.Result
: await valueTask.AsTask();
}
return total;
}
ValueTask<int> ConsumeCrazy(int repeats)
{
int total = 0;
while (repeats-- > 0)
{
ValueTask<int> valueTask = SampleUsage(); // INLINEABLE
if (valueTask.IsCompleted)
total += valueTask.Result;
else
return ContinueAsync(valueTask, repeats, total);
}
return new ValueTask<int>(total);
}
async ValueTask<int> ContinueAsync(ValueTask<int> valueTask, int repeats, int total)
{
total += await valueTask;
while (repeats-- > 0)
{
valueTask = SampleUsage();
if (valueTask.IsCompleted)
total += valueTask.Result;
else
total += await valueTask;
}
return total;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)] // super important!
ValueTask<int> SampleUsage()
=> IsFastSynchronousExecutionPossible()
? new ValueTask<int>(
result: ExecuteSynchronous()) // INLINEABLE!!!
: new ValueTask<int>(
task: ExecuteAsync());
[MethodImpl(MethodImplOptions.NoInlining)]
bool IsFastSynchronousExecutionPossible() => true;
int ExecuteSynchronous() => 1;
Task<int> ExecuteAsync() => Task.FromResult(1);
}
}