NetworkWriterPool.cs 1.7 KB

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