OnSerializeAllSafely: cache writer

This commit is contained in:
vis2k 2019-02-24 21:48:26 +01:00
parent 7323d450ad
commit 6c3401c4fe

View File

@ -447,10 +447,17 @@ internal bool OnSerializeSafely(NetworkBehaviour comp, NetworkWriter writer, boo
return result;
}
// OnSerializeAllSafely is in hot path. caching the writer is really
// worth it to avoid large amounts of allocations.
static NetworkWriter onSerializeWriter = new NetworkWriter();
// serialize all components (or only dirty ones if not initial state)
// -> returns serialized data of everything dirty, null if nothing was dirty
internal byte[] OnSerializeAllSafely(bool initialState)
{
// reset cached writer's position
onSerializeWriter.Position = 0;
if (m_NetworkBehaviours.Length > 64)
{
Debug.LogError("Only 64 NetworkBehaviour components are allowed for NetworkIdentity: " + name + " because of the dirtyComponentMask");
@ -461,8 +468,7 @@ internal byte[] OnSerializeAllSafely(bool initialState)
if (dirtyComponentsMask == 0L)
return null;
NetworkWriter writer = new NetworkWriter();
writer.WritePackedUInt64(dirtyComponentsMask); // WritePacked64 so we don't write full 8 bytes if we don't have to
onSerializeWriter.WritePackedUInt64(dirtyComponentsMask); // WritePacked64 so we don't write full 8 bytes if we don't have to
foreach (NetworkBehaviour comp in m_NetworkBehaviours)
{
@ -473,7 +479,7 @@ internal byte[] OnSerializeAllSafely(bool initialState)
{
// serialize the data
if (LogFilter.Debug) { Debug.Log("OnSerializeAllSafely: " + name + " -> " + comp.GetType() + " initial=" + initialState); }
OnSerializeSafely(comp, writer, initialState);
OnSerializeSafely(comp, onSerializeWriter, initialState);
// Clear dirty bits only if we are synchronizing data and not sending a spawn message.
// This preserves the behavior in HLAPI
@ -484,7 +490,7 @@ internal byte[] OnSerializeAllSafely(bool initialState)
}
}
return writer.ToArray();
return onSerializeWriter.ToArray();
}
private ulong GetDirtyMask(NetworkBehaviour[] components, bool initialState)