Skip to content

Commit 5203668

Browse files
Merge pull request #1759 from Mahdigln/ImproveGetEnumName
Use ConcurrentDictionary For Improving Get Enum Name
2 parents 0dd71eb + 1f815a2 commit 5203668

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

src/Microsoft.OpenApi/Extensions/EnumExtensions.cs

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// Licensed under the MIT license.
33

44
using System;
5+
using System.Collections.Concurrent;
56
using System.Diagnostics.CodeAnalysis;
67
using System.Linq;
78
using System.Reflection;
@@ -14,6 +15,9 @@ namespace Microsoft.OpenApi.Extensions
1415
/// </summary>
1516
public static class EnumExtensions
1617
{
18+
// Cache to store display names of enum values
19+
private static readonly ConcurrentDictionary<Enum, string> DisplayNameCache = new();
20+
1721
/// <summary>
1822
/// Gets an attribute on an enum field value.
1923
/// </summary>
@@ -26,7 +30,13 @@ public static class EnumExtensions
2630
public static T GetAttributeOfType<T>(this Enum enumValue) where T : Attribute
2731
{
2832
var type = enumValue.GetType();
33+
// Use GetField to get the field info for the enum value
2934
var memInfo = type.GetField(enumValue.ToString(), BindingFlags.Public | BindingFlags.Static);
35+
36+
if (memInfo == null)
37+
return null;
38+
39+
// Retrieve the custom attributes of type T
3040
var attributes = memInfo.GetCustomAttributes<T>(false);
3141
return attributes.FirstOrDefault();
3242
}
@@ -36,13 +46,20 @@ public static T GetAttributeOfType<T>(this Enum enumValue) where T : Attribute
3646
/// </summary>
3747
/// <param name="enumValue">The enum value.</param>
3848
/// <returns>
39-
/// Use <see cref="DisplayAttribute"/> if exists.
49+
/// Use <see cref="DisplayAttribute"/> if it exists.
4050
/// Otherwise, use the standard string representation.
4151
/// </returns>
4252
public static string GetDisplayName(this Enum enumValue)
4353
{
44-
var attribute = enumValue.GetAttributeOfType<DisplayAttribute>();
45-
return attribute == null ? enumValue.ToString() : attribute.Name;
54+
// Retrieve the display name from the cache if it exists
55+
return DisplayNameCache.GetOrAdd(enumValue, e =>
56+
{
57+
// Get the DisplayAttribute
58+
var attribute = e.GetAttributeOfType<DisplayAttribute>();
59+
60+
// Return the DisplayAttribute name if it exists, otherwise return the enum's string representation
61+
return attribute == null ? e.ToString() : attribute.Name;
62+
});
4663
}
4764
}
4865
}

0 commit comments

Comments
 (0)