Skip to content

Commit

Permalink
perf: avoid boxing for getting message id (#1144)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
paulpach and MichalPetryka committed Oct 13, 2019
1 parent 0024353 commit 9513842
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
7 changes: 5 additions & 2 deletions Assets/Mirror/Runtime/MessagePacker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 6 additions & 2 deletions Assets/Mirror/Runtime/NetworkConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -386,8 +386,12 @@ internal bool InvokeHandler(int msgType, NetworkReader reader, int channelId)
// 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);
Expand Down

0 comments on commit 9513842

Please sign in to comment.