-
Notifications
You must be signed in to change notification settings - Fork 0
/
EnumParse.cs
103 lines (89 loc) · 2.86 KB
/
EnumParse.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
101
102
103
using BenchmarkDotNet.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Benchmarks
{
[RyuJitX64Job]
public class EnumParse
{
private const int TestCases = 1_000_000;
string[] options = new[] { "Red", "Green", "Blue", "1", "2", "3", "unknown", "4", "123456" };
string[] dataToConvert;
Dictionary<string, Colour> mappingDict;
[GlobalSetup]
public void Setup()
{
var r = new Random();
dataToConvert =
Enumerable
.Range(1, TestCases)
.Select(_ => options[r.Next(options.Length)])
.ToArray();
mappingDict =
Enum
.GetValues(typeof(Colour))
.Cast<Colour>()
.SelectMany(v =>
new[] {
(n: v.ToString(), v),
(n: ((int)v).ToString(), v)
})
.ToDictionary(i => i.n, i => i.v, StringComparer.OrdinalIgnoreCase);
}
[Benchmark]
public Colour[] TryParseAndIsDefined()
{
return dataToConvert
.Select(startOfPath => {
if (Enum.TryParse(startOfPath, true, out Colour apiMethodGroupId) &&
Enum.IsDefined(typeof(Colour), apiMethodGroupId))
return apiMethodGroupId;
return (Colour)0;
})
.ToArray();
}
//[Benchmark]
public Colour[] IsDefinedAndTryParse()
{
return dataToConvert
.Select(startOfPath => {
if (Enum.IsDefined(typeof(Colour), startOfPath) &&
Enum.TryParse(startOfPath, true, out Colour apiMethodGroupId))
return apiMethodGroupId;
return (Colour)0;
})
.ToArray();
}
[Benchmark]
public Colour[] TryParseOnly()
{
return dataToConvert
.Select(startOfPath => {
if (Enum.TryParse(startOfPath, true, out Colour apiMethodGroupId))
return apiMethodGroupId;
return (Colour)0;
})
.ToArray();
}
[Benchmark]
public Colour[] UsingDictionary()
{
return dataToConvert
.Select(startOfPath => {
if (mappingDict.TryGetValue(startOfPath, out Colour apiMethodGroupId))
return apiMethodGroupId;
return (Colour)0;
})
.ToArray();
}
}
public enum Colour
{
Red = 1,
Green = 2,
Blue = 3
}
}