-
Notifications
You must be signed in to change notification settings - Fork 272
/
GuardedTwoClassVirtual.cs
67 lines (56 loc) · 1.76 KB
/
GuardedTwoClassVirtual.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Extensions;
using MicroBenchmarks;
// Performance test for virtual call dispatch with two
// possible target classes mixed in varying proportions.
namespace GuardedDevirtualization
{
[BenchmarkCategory(Categories.Runtime, Categories.Virtual)]
public class TwoClassVirtual
{
public class B
{
public virtual int F() => 33;
}
public class D : B
{
public override int F() => 44;
}
[Benchmark(OperationsPerInvoke = TestInput.N)]
[ArgumentsSource(nameof(GetInput))]
public long Call(TestInput testInput)
{
long sum = 0;
B[] input = testInput.Array;
for (int i = 0; i < input.Length; i++)
{
sum += input[i].F();
}
return sum;
}
public static IEnumerable<TestInput> GetInput()
{
for (double pB = 0; pB <= 1.0; pB += 0.1)
{
yield return new TestInput(pB);
}
}
public class TestInput
{
public const int N = 1000;
public B[] Array;
private double _pB;
public TestInput(double pB)
{
_pB = pB;
Array = ValuesGenerator.Array<double>(N).Select(p => p > _pB ? new D() : new B()).ToArray();
}
public override string ToString() => $"pB = {_pB:F2}";
}
}
}