aboutsummaryrefslogtreecommitdiff
path: root/csharp
diff options
context:
space:
mode:
authorJon Skeet <skeet@pobox.com>2015-06-09 19:44:24 +0100
committerJon Skeet <skeet@pobox.com>2015-06-09 19:44:24 +0100
commit954e720837be515254360cf9fdf3d9681c1bd91c (patch)
treeef0824026b8b60777749c855c423917a4671dccb /csharp
parente38294a62d7f37c0661273a9a26fda16d557423f (diff)
downloadprotobuf-954e720837be515254360cf9fdf3d9681c1bd91c.tar.gz
protobuf-954e720837be515254360cf9fdf3d9681c1bd91c.tar.bz2
protobuf-954e720837be515254360cf9fdf3d9681c1bd91c.zip
Use expression trees to avoid boxing when converting enums.
Diffstat (limited to 'csharp')
-rw-r--r--csharp/src/ProtocolBuffers/EnumHelper.cs16
1 files changed, 12 insertions, 4 deletions
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<int, T> _byNumber;
private static readonly Dictionary<string, T> _byName;
+ private static readonly Func<T, long> toRawValue;
+ private static readonly Func<long, T> 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<Func<T, long>>(convertedParam1, param1).Compile();
+ fromRawValue = Expression.Lambda<Func<long, T>>(convertedParam2, param2).Compile();
}
/// <summary>
@@ -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);
}
}