-
-
Notifications
You must be signed in to change notification settings - Fork 65
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Revert "Revert "perf: faster NetworkWriter pooling (#1616)""
This reverts commit e96b687.
- Loading branch information
Showing
1 changed file
with
18 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
} | ||
} |