Skip to content

Commit 813e6ca

Browse files
committed
Added BitWriter pooling to prevent allocating BitWriters
1 parent aca5a40 commit 813e6ca

File tree

10 files changed

+63
-59
lines changed

10 files changed

+63
-59
lines changed

MLAPI/Data/NetworkConfig.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ public byte[] GetConfig(bool cache = true)
148148
if (ConfigHash != null && cache)
149149
return ConfigHash;
150150

151-
using (BitWriter writer = new BitWriter())
151+
using (BitWriter writer = BitWriter.Get())
152152
{
153153
writer.WriteUShort(ProtocolVersion);
154154
for (int i = 0; i < Channels.Count; i++)

MLAPI/MonoBehaviours/Core/NetworkedBehaviour.cs

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ protected void InvokeCommand(string methodName, params object[] methodParams)
219219
}
220220

221221
ulong hash = Data.Cache.GetMessageAttributeHash(methodName);
222-
using (BitWriter writer = new BitWriter())
222+
using (BitWriter writer = BitWriter.Get())
223223
{
224224
writer.WriteUInt(networkId);
225225
writer.WriteUShort(networkedObject.GetOrderIndex(this));
@@ -255,7 +255,7 @@ protected void InvokeClientRpc(string methodName, params object[] methodParams)
255255
}
256256

257257
ulong hash = Data.Cache.GetMessageAttributeHash(methodName);
258-
using (BitWriter writer = new BitWriter())
258+
using (BitWriter writer = BitWriter.Get())
259259
{
260260
writer.WriteUInt(networkId);
261261
writer.WriteUShort(networkedObject.GetOrderIndex(this));
@@ -291,7 +291,7 @@ protected void InvokeTargetRpc(string methodName, params object[] methodParams)
291291
}
292292

293293
ulong hash = Data.Cache.GetMessageAttributeHash(methodName);
294-
using (BitWriter writer = new BitWriter())
294+
using (BitWriter writer = BitWriter.Get())
295295
{
296296
writer.WriteUInt(networkId);
297297
writer.WriteUShort(networkedObject.GetOrderIndex(this));
@@ -474,7 +474,7 @@ internal void FlushToClient(uint clientId)
474474
if (syncedVarFields.Count == 0)
475475
return;
476476

477-
using (BitWriter writer = new BitWriter())
477+
using (BitWriter writer = BitWriter.Get())
478478
{
479479
//Write all indexes
480480
int syncCount = 0;
@@ -531,7 +531,7 @@ internal void SyncVarUpdate()
531531
if (dirtyTargets == 0)
532532
{
533533
//It's sync time!
534-
using (BitWriter writer = new BitWriter())
534+
using (BitWriter writer = BitWriter.Get())
535535
{
536536
//Write all indexes
537537
writer.WriteByte(totalDirtyCount);
@@ -561,7 +561,7 @@ internal void SyncVarUpdate()
561561
if (!(isHost && ownerClientId == NetworkingManager.singleton.NetworkConfig.NetworkTransport.HostDummyId))
562562
{
563563
//It's sync time. This is the target receivers packet.
564-
using (BitWriter writer = new BitWriter())
564+
using (BitWriter writer = BitWriter.Get())
565565
{
566566
//Write all indexes
567567
writer.WriteByte(totalDirtyCount);
@@ -592,7 +592,7 @@ internal void SyncVarUpdate()
592592
return;
593593

594594
//It's sync time. This is the NON target receivers packet.
595-
using (BitWriter writer = new BitWriter())
595+
using (BitWriter writer = BitWriter.Get())
596596
{
597597
//Write all indexes
598598
writer.WriteByte(nonTargetDirtyCount);
@@ -665,7 +665,7 @@ protected void SendToServer(string messageType, string channelName, byte[] data)
665665
Debug.LogWarning("MLAPI: Server can not send messages to server.");
666666
return;
667667
}
668-
using (BitWriter writer = new BitWriter())
668+
using (BitWriter writer = BitWriter.Get())
669669
{
670670
writer.WriteByteArray(data);
671671
InternalMessageHandler.Send(NetworkingManager.singleton.NetworkConfig.NetworkTransport.ServerNetId, messageType, channelName, writer, null);
@@ -733,7 +733,7 @@ protected void SendToServerTarget(string messageType, string channelName, byte[]
733733
Debug.LogWarning("MLAPI: Server can not send messages to server.");
734734
return;
735735
}
736-
using (BitWriter writer = new BitWriter())
736+
using (BitWriter writer = BitWriter.Get())
737737
{
738738
writer.WriteByteArray(data);
739739
InternalMessageHandler.Send(NetworkingManager.singleton.NetworkConfig.NetworkTransport.ServerNetId, messageType, channelName, writer, null, networkId, networkedObject.GetOrderIndex(this));
@@ -803,7 +803,7 @@ protected void SendToLocalClient(string messageType, string channelName, byte[]
803803
return;
804804
}
805805
uint? fromNetId = respectObservers ? (uint?)networkId : null;
806-
using (BitWriter writer = new BitWriter())
806+
using (BitWriter writer = BitWriter.Get())
807807
{
808808
writer.WriteByteArray(data);
809809
InternalMessageHandler.Send(ownerClientId, messageType, channelName, writer, fromNetId);
@@ -874,7 +874,7 @@ protected void SendToLocalClientTarget(string messageType, string channelName, b
874874
Debug.LogWarning("MLAPI: Invalid Passthrough send. Ensure AllowPassthroughMessages are turned on and that the MessageType " + messageType + " is registered as a passthroughMessageType");
875875
return;
876876
}
877-
using (BitWriter writer = new BitWriter())
877+
using (BitWriter writer = BitWriter.Get())
878878
{
879879
writer.WriteByteArray(data);
880880
InternalMessageHandler.Send(ownerClientId, messageType, channelName, writer, null, networkId, networkedObject.GetOrderIndex(this));
@@ -944,7 +944,7 @@ protected void SendToNonLocalClients(string messageType, string channelName, byt
944944
return;
945945
}
946946
uint? fromNetId = respectObservers ? (uint?)networkId : null;
947-
using (BitWriter writer = new BitWriter())
947+
using (BitWriter writer = BitWriter.Get())
948948
{
949949
writer.WriteByteArray(data);
950950
InternalMessageHandler.Send(messageType, channelName, writer, ownerClientId, fromNetId, null, null);
@@ -1017,7 +1017,7 @@ protected void SendToNonLocalClientsTarget(string messageType, string channelNam
10171017
return;
10181018
}
10191019
uint? fromNetId = respectObservers ? (uint?)networkId : null;
1020-
using (BitWriter writer = new BitWriter())
1020+
using (BitWriter writer = BitWriter.Get())
10211021
{
10221022
writer.WriteByteArray(data);
10231023
InternalMessageHandler.Send(messageType, channelName, writer, ownerClientId, fromNetId, networkId, networkedObject.GetOrderIndex(this));
@@ -1091,7 +1091,7 @@ protected void SendToClient(uint clientId, string messageType, string channelNam
10911091
return;
10921092
}
10931093
uint? fromNetId = respectObservers ? (uint?)networkId : null;
1094-
using (BitWriter writer = new BitWriter())
1094+
using (BitWriter writer = BitWriter.Get())
10951095
{
10961096
writer.WriteByteArray(data);
10971097
InternalMessageHandler.Send(clientId, messageType, channelName, writer, fromNetId);
@@ -1168,7 +1168,7 @@ protected void SendToClientTarget(uint clientId, string messageType, string chan
11681168
return;
11691169
}
11701170
uint? fromNetId = respectObservers ? (uint?)networkId : null;
1171-
using (BitWriter writer = new BitWriter())
1171+
using (BitWriter writer = BitWriter.Get())
11721172
{
11731173
writer.WriteByteArray(data);
11741174
InternalMessageHandler.Send(clientId, messageType, channelName, writer, fromNetId, networkId, networkedObject.GetOrderIndex(this));
@@ -1244,7 +1244,7 @@ protected void SendToClients(uint[] clientIds, string messageType, string channe
12441244
return;
12451245
}
12461246
uint? fromNetId = respectObservers ? (uint?)networkId : null;
1247-
using (BitWriter writer = new BitWriter())
1247+
using (BitWriter writer = BitWriter.Get())
12481248
{
12491249
writer.WriteByteArray(data);
12501250
InternalMessageHandler.Send(clientIds, messageType, channelName, writer, fromNetId);
@@ -1320,7 +1320,7 @@ protected void SendToClientsTarget(uint[] clientIds, string messageType, string
13201320
return;
13211321
}
13221322
uint? fromNetId = respectObservers ? (uint?)networkId : null;
1323-
using (BitWriter writer = new BitWriter())
1323+
using (BitWriter writer = BitWriter.Get())
13241324
{
13251325
writer.WriteByteArray(data);
13261326
InternalMessageHandler.Send(clientIds, messageType, channelName, writer, fromNetId, networkId, networkedObject.GetOrderIndex(this));
@@ -1396,7 +1396,7 @@ protected void SendToClients(List<uint> clientIds, string messageType, string ch
13961396
return;
13971397
}
13981398
uint? fromNetId = respectObservers ? (uint?)networkId : null;
1399-
using (BitWriter writer = new BitWriter())
1399+
using (BitWriter writer = BitWriter.Get())
14001400
{
14011401
writer.WriteByteArray(data);
14021402
InternalMessageHandler.Send(clientIds, messageType, channelName, writer, fromNetId);
@@ -1472,7 +1472,7 @@ protected void SendToClientsTarget(List<uint> clientIds, string messageType, str
14721472
return;
14731473
}
14741474
uint? fromNetId = respectObservers ? (uint?)networkId : null;
1475-
using (BitWriter writer = new BitWriter())
1475+
using (BitWriter writer = BitWriter.Get())
14761476
{
14771477
writer.WriteByteArray(data);
14781478
InternalMessageHandler.Send(clientIds, messageType, channelName, writer, fromNetId, networkId, networkedObject.GetOrderIndex(this));
@@ -1547,7 +1547,7 @@ protected void SendToClients(string messageType, string channelName, byte[] data
15471547
return;
15481548
}
15491549
uint? fromNetId = respectObservers ? (uint?)networkId : null;
1550-
using (BitWriter writer = new BitWriter())
1550+
using (BitWriter writer = BitWriter.Get())
15511551
{
15521552
writer.WriteByteArray(data);
15531553
InternalMessageHandler.Send(messageType, channelName, writer, fromNetId);
@@ -1620,7 +1620,7 @@ protected void SendToClientsTarget(string messageType, string channelName, byte[
16201620
return;
16211621
}
16221622
uint? fromNetId = respectObservers ? (uint?)networkId : null;
1623-
using (BitWriter writer = new BitWriter())
1623+
using (BitWriter writer = BitWriter.Get())
16241624
{
16251625
writer.WriteByteArray(data);
16261626
InternalMessageHandler.Send(messageType, channelName, writer, fromNetId, networkId, networkedObject.GetOrderIndex(this));

MLAPI/MonoBehaviours/Core/NetworkedObject.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ internal void RebuildObservers(uint? clientId = null)
183183
(!previousObservers.Contains(pair.Key) && observers.Contains(pair.Key)))
184184
{
185185
//Something changed for this client.
186-
using (BitWriter writer = new BitWriter())
186+
using (BitWriter writer = BitWriter.Get())
187187
{
188188
writer.WriteUInt(networkId);
189189
writer.WriteBool(observers.Contains(pair.Key));

MLAPI/MonoBehaviours/Core/NetworkingManager.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -687,7 +687,7 @@ private void Update()
687687
diffiePublic = clientDiffieHellman.GetPublicKey();
688688
}
689689

690-
using (BitWriter writer = new BitWriter())
690+
using (BitWriter writer = BitWriter.Get())
691691
{
692692
writer.WriteByteArray(NetworkConfig.GetConfig(), true);
693693

@@ -999,7 +999,7 @@ internal void OnClientDisconnect(uint clientId)
999999
foreach (KeyValuePair<uint, NetworkedObject> pair in SpawnManager.spawnedObjects)
10001000
pair.Value.observers.Remove(clientId);
10011001

1002-
using (BitWriter writer = new BitWriter())
1002+
using (BitWriter writer = BitWriter.Get())
10031003
{
10041004
writer.WriteUInt(clientId);
10051005
InternalMessageHandler.Send("MLAPI_CLIENT_DISCONNECT", "MLAPI_INTERNAL", writer, clientId, null);
@@ -1009,7 +1009,7 @@ internal void OnClientDisconnect(uint clientId)
10091009

10101010
private void SyncTime()
10111011
{
1012-
using (BitWriter writer = new BitWriter())
1012+
using (BitWriter writer = BitWriter.Get())
10131013
{
10141014
writer.WriteFloat(NetworkTime);
10151015
int timestamp = NetworkConfig.NetworkTransport.GetNetworkTimestamp();
@@ -1065,7 +1065,7 @@ internal void HandleApproval(uint clientId, bool approved, Vector3 position, Qua
10651065

10661066
int amountOfObjectsToSend = SpawnManager.spawnedObjects.Values.Count;
10671067

1068-
using (BitWriter writer = new BitWriter())
1068+
using (BitWriter writer = BitWriter.Get())
10691069
{
10701070
writer.WriteUInt(clientId);
10711071
if (NetworkConfig.EnableSceneSwitching)
@@ -1125,7 +1125,7 @@ internal void HandleApproval(uint clientId, bool approved, Vector3 position, Qua
11251125

11261126
//Inform old clients of the new player
11271127

1128-
using (BitWriter writer = new BitWriter())
1128+
using (BitWriter writer = BitWriter.Get())
11291129
{
11301130
if (NetworkConfig.HandleObjectSpawning)
11311131
{

MLAPI/NetworkingManagerComponents/Binary/BinarySerializer.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ public static byte[] Serialize<T>(T instance)
4040
cachedFields.Add(instance.GetType().FullName, sortedFields);
4141
}
4242

43-
using (BitWriter writer = new BitWriter())
43+
using (BitWriter writer = BitWriter.Get())
4444
{
4545
for (int i = 0; i < sortedFields.Length; i++)
4646
{

MLAPI/NetworkingManagerComponents/Binary/BitWriter.cs

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public Partial(byte value, byte count)
2424
}
2525
}
2626

27-
private static readonly Queue<List<object>> listPool = new Queue<List<object>>();
27+
private static readonly Queue<BitWriter> writerPool = new Queue<BitWriter>();
2828

2929
private static readonly float[] holder_f = new float[1];
3030
private static readonly double[] holder_d = new double[1];
@@ -63,28 +63,34 @@ static BitWriter()
6363

6464
for (int i = 0; i < 10; i++)
6565
{
66-
listPool.Enqueue(new List<object>());
66+
writerPool.Enqueue(new BitWriter());
6767
}
6868
}
6969

70-
private List<object> collect = null;
71-
private bool tempAlloc = false;
70+
private readonly List<object> collect = new List<object>();
71+
private bool outsidePool = false;
7272

7373
/// <summary>
74-
/// Allocates a new binary collector.
74+
/// Allocates a new binary collector. This is only used when there are no more writers in the pool
7575
/// </summary>
76-
public BitWriter()
76+
private BitWriter()
7777
{
78-
if (listPool.Count == 0)
78+
79+
}
80+
81+
/// <summary>
82+
/// Returns a BitWriter from the pool
83+
/// </summary>
84+
/// <returns></returns>
85+
public static BitWriter Get()
86+
{
87+
if (writerPool.Count == 0)
7988
{
8089
Debug.LogWarning("MLAPI: There can be no more than 10 BitWriters. Have you forgotten do dispose? (It will still work with worse performance)");
81-
collect = new List<object>();
82-
tempAlloc = true;
90+
return new BitWriter() { outsidePool = true };
8391
}
8492
else
85-
{
86-
collect = listPool.Dequeue();
87-
}
93+
return writerPool.Dequeue();
8894
}
8995

9096
private void Push<T>(T b)
@@ -425,15 +431,13 @@ private static int BytesToRead(object i)
425431
// Supported datatypes for serialization
426432
private static bool IsSupportedType(Type t) => supportedTypes.Contains(t);
427433

428-
// Creates a weak reference to the allocated collector so that reuse may be possible
429434
public void Dispose()
430435
{
431-
if (!tempAlloc)
436+
if (!outsidePool)
432437
{
433438
collect.Clear();
434-
listPool.Enqueue(collect);
439+
writerPool.Enqueue(this);
435440
}
436-
collect = null; //GC picks this
437441
}
438442
}
439443
}

MLAPI/NetworkingManagerComponents/Core/InternalMessageHandler.Send.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ internal static void PassthroughSend(uint targetId, uint sourceId, ushort messag
1818
return;
1919
}
2020

21-
using (BitWriter writer = new BitWriter())
21+
using (BitWriter writer = BitWriter.Get())
2222
{
2323
writer.WriteUShort(messageType);
2424
writer.WriteBool(networkId != null);
@@ -72,7 +72,7 @@ internal static bool Send(uint clientId, string messageType, string channelName,
7272
return true;
7373
}
7474

75-
using (BitWriter writer = new BitWriter())
75+
using (BitWriter writer = BitWriter.Get())
7676
{
7777
writer.WriteUShort(MessageManager.messageTypes[messageType]);
7878
writer.WriteBool(networkId != null);
@@ -127,7 +127,7 @@ internal static void Send(uint[] clientIds, string messageType, string channelNa
127127
return;
128128
}
129129

130-
using (BitWriter writer = new BitWriter())
130+
using (BitWriter writer = BitWriter.Get())
131131
{
132132
writer.WriteUShort(MessageManager.messageTypes[messageType]);
133133
writer.WriteBool(networkId != null);
@@ -179,7 +179,7 @@ internal static void Send(List<uint> clientIds, string messageType, string chann
179179
return;
180180
}
181181

182-
using (BitWriter writer = new BitWriter())
182+
using (BitWriter writer = BitWriter.Get())
183183
{
184184
writer.WriteUShort(MessageManager.messageTypes[messageType]);
185185
writer.WriteBool(networkId != null);
@@ -236,7 +236,7 @@ internal static ref List<uint> Send(string messageType, string channelName, BitW
236236
return ref failedObservers;
237237
}
238238

239-
using (BitWriter writer = new BitWriter())
239+
using (BitWriter writer = BitWriter.Get())
240240
{
241241
writer.WriteUShort(MessageManager.messageTypes[messageType]);
242242
writer.WriteBool(networkId != null);
@@ -294,7 +294,7 @@ internal static ref List<uint> Send(string messageType, string channelName, BitW
294294
return ref failedObservers;
295295
}
296296

297-
using (BitWriter writer = new BitWriter())
297+
using (BitWriter writer = BitWriter.Get())
298298
{
299299
writer.WriteUShort(MessageManager.messageTypes[messageType]);
300300
writer.WriteBool(networkId != null);

0 commit comments

Comments
 (0)