Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve performance of Enum's generic IsDefined / GetName / GetValues / GetNames #44355

Merged
merged 1 commit into from
Nov 7, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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),
};
EgorBo marked this conversation as resolved.
Show resolved Hide resolved
#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