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:
James Frowen 2020-03-28 17:58:00 +00:00 committed by GitHub
parent 61163cacb4
commit 5128b122fe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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();
return new PooledNetworkWriter();
}
PooledNetworkWriter writer = pool[next];
pool[next] = null;
next--;
// reset cached writer length and position
writer.SetLength(0);
return writer;
}
return new PooledNetworkWriter();
}
public static void Recycle(PooledNetworkWriter writer)
{
pool.Push(writer);
if ((next + 1) < MaxPoolSize)
{
next++;
pool[next] = writer;
}
}
}
}