From 954e720837be515254360cf9fdf3d9681c1bd91c Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Tue, 9 Jun 2015 19:44:24 +0100 Subject: Use expression trees to avoid boxing when converting enums. --- csharp/src/ProtocolBuffers/EnumHelper.cs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) (limited to 'csharp') diff --git a/csharp/src/ProtocolBuffers/EnumHelper.cs b/csharp/src/ProtocolBuffers/EnumHelper.cs index 7e76d71b..1cf18985 100644 --- a/csharp/src/ProtocolBuffers/EnumHelper.cs +++ b/csharp/src/ProtocolBuffers/EnumHelper.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Linq.Expressions; using System.Text; namespace Google.Protobuf @@ -10,6 +11,8 @@ namespace Google.Protobuf // TODO(jonskeet): For snmall enums, use something lighter-weight than a dictionary? private static readonly Dictionary _byNumber; private static readonly Dictionary _byName; + private static readonly Func toRawValue; + private static readonly Func fromRawValue; private const long UnknownValueBase = 0x100000000L; @@ -36,6 +39,13 @@ namespace Google.Protobuf { _byName[name] = (T) Enum.Parse(typeof(T), name, false); } + + ParameterExpression param1 = Expression.Parameter(typeof(T), "x"); + ParameterExpression param2 = Expression.Parameter(typeof(long), "x"); + Expression convertedParam1 = Expression.Convert(param1, typeof(long)); + Expression convertedParam2 = Expression.Convert(param2, typeof(T)); + toRawValue = Expression.Lambda>(convertedParam1, param1).Compile(); + fromRawValue = Expression.Lambda>(convertedParam2, param2).Compile(); } /// @@ -71,14 +81,12 @@ namespace Google.Protobuf private static long GetRawValue(T value) { - // TODO(jonskeet): Try using expression trees to get rid of the boxing here. - return (long)(object)value; + return toRawValue(value); } private static T FromRawValue(long value) { - // TODO(jonskeet): Try using expression trees to get rid of the boxing here. - return (T)(object)value; + return fromRawValue(value); } } -- cgit v1.2.3