Skip to content

Commit

Permalink
Use ConcurrentDictionary For Improving Get Enum Name
Browse files Browse the repository at this point in the history
  • Loading branch information
Mahdi Golestan authored and Mahdi Golestan committed Jul 27, 2024
1 parent afbc27d commit 1f815a2
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions src/Microsoft.OpenApi/Extensions/EnumExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -14,6 +15,9 @@ namespace Microsoft.OpenApi.Extensions
/// </summary>
public static class EnumExtensions
{
// Cache to store display names of enum values
private static readonly ConcurrentDictionary<Enum, string> DisplayNameCache = new();

/// <summary>
/// Gets an attribute on an enum field value.
/// </summary>
Expand All @@ -26,7 +30,13 @@ public static class EnumExtensions
public static T GetAttributeOfType<T>(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<T>(false);
return attributes.FirstOrDefault();
}
Expand All @@ -36,13 +46,20 @@ public static T GetAttributeOfType<T>(this Enum enumValue) where T : Attribute
/// </summary>
/// <param name="enumValue">The enum value.</param>
/// <returns>
/// Use <see cref="DisplayAttribute"/> if exists.
/// Use <see cref="DisplayAttribute"/> if it exists.
/// Otherwise, use the standard string representation.
/// </returns>
public static string GetDisplayName(this Enum enumValue)
{
var attribute = enumValue.GetAttributeOfType<DisplayAttribute>();
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<DisplayAttribute>();
// Return the DisplayAttribute name if it exists, otherwise return the enum's string representation
return attribute == null ? e.ToString() : attribute.Name;
});
}
}
}

0 comments on commit 1f815a2

Please sign in to comment.