-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathEqualityComparer.cs
100 lines (82 loc) · 2.91 KB
/
EqualityComparer.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
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
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ShallowDeepCopy
{
public class PrimaryColorComparer : EqualityComparer<PrimaryColor>
{
public override bool Equals(PrimaryColor x, PrimaryColor y)
{
return Default.Equals(x, y); // direct comparison "==" is of same execution time in .Net 5 +
}
public override int GetHashCode([DisallowNull] PrimaryColor obj)
{
return Default.GetHashCode(obj); // obj.GetHashCode() is of same execution time in .Net 5 +
}
}
public enum PrimaryColor { Red, Yellow, Blue }
[MemoryDiagnoser]
public class CompareEnum
{
public PrimaryColor firstPrimaryColor => PrimaryColor.Blue;
public PrimaryColor secondPrimaryColor => PrimaryColor.Blue;
public bool GenericBoxing<T>(T firstEnum, T secondEnum) where T : Enum
{
return firstEnum.Equals(secondEnum);
}
public bool GenericBoxingEnumEquals<T>(T firstEnum, T secondEnum) where T : Enum
{
return Enum.Equals(firstEnum,secondEnum);
}
public bool GenericEqualityComparer<T>(T firstEnum, T secondEnum) where T : Enum
{
return EqualityComparer<T>.Default.Equals(firstEnum,secondEnum);
}
[Benchmark]
public void GenericBoxingTest()
{
for (int i = 0; i < 10_000; i++)
{
bool arePrimaryColorsEqualBoxing = GenericBoxing<PrimaryColor>(firstPrimaryColor, secondPrimaryColor); // ~ 160 micro seconds
}
}
[Benchmark]
public void GenericBoxingEnumEqualsTest()
{
for (int i = 0; i < 10_000; i++)
{
bool arePrimaryColorsEqualEnum = GenericBoxingEnumEquals<PrimaryColor>(firstPrimaryColor, secondPrimaryColor); // ~ 180 micro seconds
}
}
[Benchmark]
public void GenericEqualityComparerTest()
{
for (int i = 0; i < 10_000; i++)
{
bool arePrimaryColorsEqComparer = GenericEqualityComparer<PrimaryColor>(firstPrimaryColor, secondPrimaryColor); // ~ 3 micro seconds
}
}
[Benchmark]
public void PrimaryColorComparerEqualsTest()
{
PrimaryColorComparer comparer = new();
for (int i = 0; i < 10_000; i++)
{
bool arePrimaryColorsEqualDerived = comparer.Equals(firstPrimaryColor, secondPrimaryColor); // ~ 3 micro seconds
}
}
}
class Program
{
static void Main(string[] args)
{
var a = BenchmarkRunner.Run<CompareEnum>();
}
}
}