perf: avoid allocation with message structs (#939)

* avoid allocation with message structs

* Use ternary operator instead of if

* Explain witchcraft
This commit is contained in:
Paul Pacheco 2019-07-29 07:50:09 -05:00 committed by vis2k
parent b4077c1112
commit 7c7c910a5e

View File

@ -8,7 +8,11 @@ public struct NetworkMessage
public TMsg ReadMessage<TMsg>() where TMsg : IMessageBase, new()
{
TMsg msg = new TMsg();
// Normally I would just do:
// TMsg msg = new TMsg();
// but mono calls an expensive method Activator.CreateInstance
// For value types this is unnecesary, just use the default value
TMsg msg = typeof(TMsg).IsValueType ? default(TMsg) : new TMsg();
msg.Deserialize(reader);
return msg;
}