Oto bardzo szybkie rozwiązanie, które nadużywa faktu że środowisko wykonawcze tworzy wiele wystąpień statycznych klas ogólnych. Uwolnij swoje wewnętrzne demony optymalizacji!
To naprawdę świeci, gdy czytasz Odmiany w strumieniu w sposób ogólny. Połączyć z klasą zewnętrzną, która również buforuje podstawowy typ enum i BitConverter, aby uwolnić niesamowite.
void Main()
{
Console.WriteLine("Cast (reference): {0}", (TestEnum)5);
Console.WriteLine("EnumConverter: {0}", EnumConverter<TestEnum>.Convert(5));
Console.WriteLine("Enum.ToObject: {0}", Enum.ToObject(typeof(TestEnum), 5));
int iterations = 1000 * 1000 * 100;
Measure(iterations, "Cast (reference)",() => { var t = (TestEnum)5; });
Measure(iterations, "EnumConverter",() => EnumConverter<TestEnum>.Convert(5));
Measure(iterations, "Enum.ToObject",() => Enum.ToObject(typeof(TestEnum), 5));
}
static class EnumConverter<TEnum> where TEnum : struct, IConvertible
{
public static readonly Func<long, TEnum> Convert = GenerateConverter();
static Func<long, TEnum> GenerateConverter()
{
var parameter = Expression.Parameter(typeof(long));
var dynamicMethod = Expression.Lambda<Func<long, TEnum>>(
Expression.Convert(parameter, typeof(TEnum)),
parameter);
return dynamicMethod.Compile();
}
}
enum TestEnum
{
Value = 5
}
static void Measure(int repetitions, string what, Action action)
{
action();
var total = Stopwatch.StartNew();
for (int i = 0; i < repetitions; i++)
{
action();
}
Console.WriteLine("{0}: {1}", what, total.Elapsed);
}
wyników na podstawowej i7-3740QM z optymalizacji włączona:
Cast (reference): Value
EnumConverter: Value
Enum.ToObject: Value
Cast (reference): 00:00:00.3175615
EnumConverter: 00:00:00.4335949
Enum.ToObject: 00:00:14.3396366
http://stackoverflow.com/questions/2745320/enum-tryparse-with-flags-attribute - może pomóc ? – Sunny
Ostatnia odpowiedź na http://stackoverflow.com/questions/1331739/enum-type-constraints-in-c-sharp, jest bliżej tego, co chcesz. Nadal nie jest to sprytne. Używam do tego celu refleksji, możesz uczynić kod znacznie silniejszym. Struct nie jest wystarczająco powściągliwy, aby w moim przekonaniu zarabiać na generykach. –
Coś, co nie działa: [c-sharp-non-boxing-conversion-of-generic-enum-to-int] (http://stackoverflow.com/questions/1189144/c-sharp-non-boxing- konwersja-generic-enum-to-int) – nawfal