NetworkWriterPool.cs 1.3 KB

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