mirror of
https://github.com/MirrorNetworking/Mirror.git
synced 2024-11-18 11:00:32 +00:00
perf: faster NetworkWriter pooling (#1616)
Stack turned out to be slow way to pool NetworkWriters. Replace them with an array see #1614
This commit is contained in:
parent
61163cacb4
commit
5128b122fe
@ -1,9 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Mirror
|
||||
{
|
||||
// a NetworkWriter that will recycle itself when disposed
|
||||
public class PooledNetworkWriter : NetworkWriter, IDisposable
|
||||
{
|
||||
public void Dispose()
|
||||
@ -11,27 +9,36 @@ public void Dispose()
|
||||
NetworkWriterPool.Recycle(this);
|
||||
}
|
||||
}
|
||||
|
||||
public static class NetworkWriterPool
|
||||
{
|
||||
static readonly Stack<PooledNetworkWriter> pool = new Stack<PooledNetworkWriter>();
|
||||
public const int MaxPoolSize = 10;
|
||||
|
||||
static readonly PooledNetworkWriter[] pool = new PooledNetworkWriter[MaxPoolSize];
|
||||
static int next = -1;
|
||||
|
||||
public static PooledNetworkWriter GetWriter()
|
||||
{
|
||||
if (pool.Count != 0)
|
||||
if (next == -1)
|
||||
{
|
||||
PooledNetworkWriter writer = pool.Pop();
|
||||
// reset cached writer length and position
|
||||
writer.SetLength(0);
|
||||
return writer;
|
||||
return new PooledNetworkWriter();
|
||||
}
|
||||
|
||||
return new PooledNetworkWriter();
|
||||
PooledNetworkWriter writer = pool[next];
|
||||
pool[next] = null;
|
||||
next--;
|
||||
|
||||
// reset cached writer length and position
|
||||
writer.SetLength(0);
|
||||
return writer;
|
||||
}
|
||||
|
||||
public static void Recycle(PooledNetworkWriter writer)
|
||||
{
|
||||
pool.Push(writer);
|
||||
if ((next + 1) < MaxPoolSize)
|
||||
{
|
||||
next++;
|
||||
pool[next] = writer;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user