From 7c7c910a5e5ce15dc81b1008e4797222abe7fd9a Mon Sep 17 00:00:00 2001 From: Paul Pacheco Date: Mon, 29 Jul 2019 07:50:09 -0500 Subject: [PATCH] perf: avoid allocation with message structs (#939) * avoid allocation with message structs * Use ternary operator instead of if * Explain witchcraft --- Assets/Mirror/Runtime/NetworkMessage.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Assets/Mirror/Runtime/NetworkMessage.cs b/Assets/Mirror/Runtime/NetworkMessage.cs index caa50b6f4..9e9613cdc 100644 --- a/Assets/Mirror/Runtime/NetworkMessage.cs +++ b/Assets/Mirror/Runtime/NetworkMessage.cs @@ -8,7 +8,11 @@ public struct NetworkMessage public TMsg ReadMessage() 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; }