perf: avoid boxing for getting message id (#1144)

* perf: avoid boxing for getting message id

* Update Assets/Mirror/Runtime/MessagePacker.cs

Co-Authored-By: MichalPetryka <35800402+MichalPetryka@users.noreply.github.com>

* Update Assets/Mirror/Runtime/NetworkConnection.cs

Co-Authored-By: MichalPetryka <35800402+MichalPetryka@users.noreply.github.com>
This commit is contained in:
Paul Pacheco 2019-10-13 15:57:39 -05:00 committed by GitHub
parent 0024353d44
commit 95138427f3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 4 deletions

View File

@ -59,8 +59,11 @@ public static byte[] PackMessage(int msgType, MessageBase msg)
// and do an allocation free send before recycling it.
public static void Pack<T>(T message, NetworkWriter writer) where T : IMessageBase
{
// write message type
int msgType = GetId(message.GetType());
// if it is a value type, just use typeof(T) to avoid boxing
// this works because value types cannot be derived
// if it is a reference type (for example IMessageBase),
// ask the message for the real type
int msgType = GetId(typeof(T).IsValueType ? typeof(T) : message.GetType());
writer.WriteUInt16((ushort)msgType);
// serialize message into writer

View File

@ -386,8 +386,12 @@ public bool InvokeHandler<T>(T msg, int channelId) where T : IMessageBase
// get writer from pool
NetworkWriter writer = NetworkWriterPool.GetWriter();
// pack and invoke
int msgType = MessagePacker.GetId(msg.GetType());
// if it is a value type, just use typeof(T) to avoid boxing
// this works because value types cannot be derived
// if it is a reference type (for example IMessageBase),
// ask the message for the real type
int msgType = MessagePacker.GetId(typeof(T).IsValueType ? typeof(T) : msg.GetType());
MessagePacker.Pack(msg, writer);
ArraySegment<byte> segment = writer.ToArraySegment();
bool result = InvokeHandler(msgType, new NetworkReader(segment), channelId);