perf: replace isValueType with faster alternative (#1617)

According to vis benchmark here https://github.com/vis2k/Mirror/issues/1614#issuecomment-605443808
isValueType is an expensive operation.

This microoptimization replaces isValueType for a faster (not so readable) alternative
This commit is contained in:
Paul Pacheco 2020-03-28 12:27:42 -05:00 committed by GitHub
parent 166b8c9467
commit 61163cacb4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 5 additions and 3 deletions

View File

@ -39,7 +39,7 @@ public static void Pack<T>(T message, NetworkWriter writer) where T : IMessageBa
// 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
@ -126,7 +126,9 @@ internal static NetworkMessageDelegate MessageHandler<T, C>(Action<C, T> handler
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)

View File

@ -239,7 +239,7 @@ public bool InvokeHandler<T>(T msg, int channelId) where T : IMessageBase
// 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();