Skip to content

Commit

Permalink
Improve performance of Enum's generic IsDefined / GetName / GetNames (#…
Browse files Browse the repository at this point in the history
…44355)

Eliminates the boxing in IsDefined/GetName/GetValues, and in GetNames avoids having to go through RuntimeType's GetEnumNames override.
  • Loading branch information
stephentoub authored Nov 7, 2020
1 parent a057f27 commit 6cfef20
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions src/libraries/System.Private.CoreLib/src/System/Enum.cs
Original file line number Diff line number Diff line change
Expand Up @@ -258,11 +258,26 @@ internal static ulong ToUInt64(object value)
return result;
}

private static ulong ToUInt64<TEnum>(TEnum value) where TEnum : struct, Enum =>
Type.GetTypeCode(typeof(TEnum)) switch
{
TypeCode.SByte => (ulong)Unsafe.As<TEnum, sbyte>(ref value),
TypeCode.Byte => Unsafe.As<TEnum, byte>(ref value),
TypeCode.Boolean => Convert.ToByte(Unsafe.As<TEnum, bool>(ref value)),
TypeCode.Int16 => (ulong)Unsafe.As<TEnum, short>(ref value),
TypeCode.UInt16 => Unsafe.As<TEnum, ushort>(ref value),
TypeCode.Char => Unsafe.As<TEnum, char>(ref value),
TypeCode.UInt32 => Unsafe.As<TEnum, uint>(ref value),
TypeCode.Int32 => (ulong)Unsafe.As<TEnum, int>(ref value),
TypeCode.UInt64 => Unsafe.As<TEnum, ulong>(ref value),
TypeCode.Int64 => (ulong)Unsafe.As<TEnum, long>(ref value),
_ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType),
};
#endregion

#region Public Static Methods
public static string? GetName<TEnum>(TEnum value) where TEnum : struct, Enum
=> GetName(typeof(TEnum), value);
=> GetEnumName((RuntimeType)typeof(TEnum), ToUInt64(value));

public static string? GetName(Type enumType, object value)
{
Expand All @@ -273,7 +288,7 @@ internal static ulong ToUInt64(object value)
}

public static string[] GetNames<TEnum>() where TEnum : struct, Enum
=> GetNames(typeof(TEnum));
=> new ReadOnlySpan<string>(InternalGetNames((RuntimeType)typeof(TEnum))).ToArray();

public static string[] GetNames(Type enumType)
{
Expand Down

0 comments on commit 6cfef20

Please sign in to comment.