From 1f815a2c11f8a79023a84ceceb0e08ca79927808 Mon Sep 17 00:00:00 2001 From: Mahdi Golestan Date: Sat, 27 Jul 2024 14:54:11 +0330 Subject: [PATCH] Use ConcurrentDictionary For Improving Get Enum Name --- .../Extensions/EnumExtensions.cs | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi/Extensions/EnumExtensions.cs b/src/Microsoft.OpenApi/Extensions/EnumExtensions.cs index 1eadaa5f4..bc4e86783 100644 --- a/src/Microsoft.OpenApi/Extensions/EnumExtensions.cs +++ b/src/Microsoft.OpenApi/Extensions/EnumExtensions.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. using System; +using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; @@ -14,6 +15,9 @@ namespace Microsoft.OpenApi.Extensions /// public static class EnumExtensions { + // Cache to store display names of enum values + private static readonly ConcurrentDictionary DisplayNameCache = new(); + /// /// Gets an attribute on an enum field value. /// @@ -26,7 +30,13 @@ public static class EnumExtensions public static T GetAttributeOfType(this Enum enumValue) where T : Attribute { var type = enumValue.GetType(); + // Use GetField to get the field info for the enum value var memInfo = type.GetField(enumValue.ToString(), BindingFlags.Public | BindingFlags.Static); + + if (memInfo == null) + return null; + + // Retrieve the custom attributes of type T var attributes = memInfo.GetCustomAttributes(false); return attributes.FirstOrDefault(); } @@ -36,13 +46,20 @@ public static T GetAttributeOfType(this Enum enumValue) where T : Attribute /// /// The enum value. /// - /// Use if exists. + /// Use if it exists. /// Otherwise, use the standard string representation. /// public static string GetDisplayName(this Enum enumValue) { - var attribute = enumValue.GetAttributeOfType(); - return attribute == null ? enumValue.ToString() : attribute.Name; + // Retrieve the display name from the cache if it exists + return DisplayNameCache.GetOrAdd(enumValue, e => + { + // Get the DisplayAttribute + var attribute = e.GetAttributeOfType(); + + // Return the DisplayAttribute name if it exists, otherwise return the enum's string representation + return attribute == null ? e.ToString() : attribute.Name; + }); } } }