Skip to content

Commit

Permalink
perf: replace isValueType with faster alternative (#1617)
Browse files Browse the repository at this point in the history
According to vis benchmark here MirrorNetworking/Mirror#1614 (comment)
isValueType is an expensive operation.

This microoptimization replaces isValueType for a faster (not so readable) alternative
  • Loading branch information
paulpach committed Mar 28, 2020
1 parent 166b8c9 commit 61163ca
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 3 deletions.
6 changes: 4 additions & 2 deletions Assets/Mirror/Runtime/MessagePacker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public static int GetId(Type type)
// 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());
int msgType = GetId(default(T) != null ? typeof(T) : message.GetType());
writer.WriteUInt16((ushort)msgType);

// serialize message into writer
Expand Down Expand Up @@ -126,7 +126,9 @@ public static bool UnpackMessage(NetworkReader messageReader, out int msgType)
return;
}
message = typeof(T).IsValueType ? default(T) : new T();
// if it is a value type, just use defult(T)
// otherwise allocate a new instance
message = default(T) != null ? default(T) : new T();
message.Deserialize(reader);
}
catch (Exception exception)
Expand Down
2 changes: 1 addition & 1 deletion Assets/Mirror/Runtime/NetworkConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ internal bool InvokeHandler(int msgType, NetworkReader reader, int channelId)
// 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());
int msgType = MessagePacker.GetId(default(T) != null ? typeof(T) : msg.GetType());

MessagePacker.Pack(msg, writer);
ArraySegment<byte> segment = writer.ToArraySegment();
Expand Down

0 comments on commit 61163ca

Please sign in to comment.