NetworkWriterPool.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using System;
  2. namespace Mirror
  3. {
  4. /// <summary>Pooled NetworkWriter, automatically returned to pool when using 'using'</summary>
  5. public sealed class PooledNetworkWriter : NetworkWriter, IDisposable
  6. {
  7. public void Dispose() => NetworkWriterPool.Recycle(this);
  8. }
  9. /// <summary>Pool of NetworkWriters to avoid allocations.</summary>
  10. public static class NetworkWriterPool
  11. {
  12. // reuse Pool<T>
  13. // we still wrap it in NetworkWriterPool.Get/Recycle so we can reset the
  14. // position before reusing.
  15. // this is also more consistent with NetworkReaderPool where we need to
  16. // assign the internal buffer before reusing.
  17. static readonly Pool<PooledNetworkWriter> Pool = new Pool<PooledNetworkWriter>(
  18. () => new PooledNetworkWriter(),
  19. // initial capacity to avoid allocations in the first few frames
  20. // 1000 * 1200 bytes = around 1 MB.
  21. 1000
  22. );
  23. /// <summary>Get a writer from the pool. Creates new one if pool is empty.</summary>
  24. public static PooledNetworkWriter GetWriter()
  25. {
  26. // grab from pool & reset position
  27. PooledNetworkWriter writer = Pool.Take();
  28. writer.Reset();
  29. return writer;
  30. }
  31. /// <summary>Return a writer to the pool.</summary>
  32. public static void Recycle(PooledNetworkWriter writer)
  33. {
  34. Pool.Return(writer);
  35. }
  36. }
  37. }