Skip to content

Commit dfd6aeb

Browse files
Merge pull request #1809 from Mahdigln/GetEnumFromDisplayName
Use ConcurrentDictionary For Improving GetEnumFromDisplayName
2 parents 6123803 + 83c9278 commit dfd6aeb

File tree

1 file changed

+15
-7
lines changed

1 file changed

+15
-7
lines changed
Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Copyright (c) Microsoft Corporation. All rights reserved.
22
// Licensed under the MIT license.
3-
43
using System;
4+
using System.Collections.Concurrent;
55
using System.Diagnostics.CodeAnalysis;
66
using System.Reflection;
77
using Microsoft.OpenApi.Attributes;
@@ -13,6 +13,8 @@ namespace Microsoft.OpenApi.Extensions
1313
/// </summary>
1414
public static class StringExtensions
1515
{
16+
private static readonly ConcurrentDictionary<Type, ConcurrentDictionary<string, object>> EnumDisplayCache = new();
17+
1618
/// <summary>
1719
/// Gets the enum value based on the given enum type and display name.
1820
/// </summary>
@@ -21,22 +23,28 @@ public static class StringExtensions
2123
{
2224
var type = typeof(T);
2325
if (!type.IsEnum)
24-
{
2526
return default;
26-
}
27+
28+
var displayMap = EnumDisplayCache.GetOrAdd(type, _ => new ConcurrentDictionary<string, object>(StringComparer.OrdinalIgnoreCase));
29+
30+
if (displayMap.TryGetValue(displayName, out var cachedValue))
31+
return (T)cachedValue;
32+
2733

2834
foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.Static))
2935
{
30-
var displayAttribute = (DisplayAttribute)field.GetCustomAttribute(typeof(DisplayAttribute));
31-
if (displayAttribute != null && displayAttribute.Name == displayName)
36+
var displayAttribute = field.GetCustomAttribute<DisplayAttribute>();
37+
if (displayAttribute != null && displayAttribute.Name.Equals(displayName, StringComparison.OrdinalIgnoreCase))
3238
{
33-
return (T)field.GetValue(null);
39+
var enumValue = (T)field.GetValue(null);
40+
displayMap.TryAdd(displayName, enumValue);
41+
return enumValue;
3442
}
3543
}
3644

3745
return default;
3846
}
3947
internal static string ToFirstCharacterLowerCase(this string input)
40-
=> string.IsNullOrEmpty(input) ? string.Empty : char.ToLowerInvariant(input[0]) + input.Substring(1);
48+
=> string.IsNullOrEmpty(input) ? string.Empty : char.ToLowerInvariant(input[0]) + input.Substring(1);
4149
}
4250
}

0 commit comments

Comments
 (0)