Skip to content

Commit

Permalink
Revert "Revert "perf: faster NetworkWriter pooling (#1616)""
Browse files Browse the repository at this point in the history
This reverts commit e96b687.
  • Loading branch information
paulpach committed Mar 29, 2020
1 parent 3307e36 commit 20e9e5d
Showing 1 changed file with 18 additions and 11 deletions.
29 changes: 18 additions & 11 deletions Assets/Mirror/Runtime/NetworkWriterPool.cs
Original file line number Diff line number Diff line change
@@ -1,37 +1,44 @@
using System;
using System.Collections.Generic;

namespace Mirror
{
// a NetworkWriter that will recycle itself when disposed
public class PooledNetworkWriter : NetworkWriter, IDisposable
{
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;
}
}
}
}

0 comments on commit 20e9e5d

Please sign in to comment.