Pool.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Pool to avoid allocations (from libuv2k)
  2. // API consistent with Microsoft's ObjectPool<T>.
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Runtime.CompilerServices;
  6. namespace Mirror
  7. {
  8. public class Pool<T>
  9. {
  10. // Mirror is single threaded, no need for concurrent collections
  11. readonly Stack<T> objects = new Stack<T>();
  12. // some types might need additional parameters in their constructor, so
  13. // we use a Func<T> generator
  14. readonly Func<T> objectGenerator;
  15. public Pool(Func<T> objectGenerator, int initialCapacity)
  16. {
  17. this.objectGenerator = objectGenerator;
  18. // allocate an initial pool so we have fewer (if any)
  19. // allocations in the first few frames (or seconds).
  20. for (int i = 0; i < initialCapacity; ++i)
  21. objects.Push(objectGenerator());
  22. }
  23. // DEPRECATED 2022-03-10
  24. [Obsolete("Take() was renamed to Get()")]
  25. public T Take() => Get();
  26. // take an element from the pool, or create a new one if empty
  27. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  28. public T Get() => objects.Count > 0 ? objects.Pop() : objectGenerator();
  29. // return an element to the pool
  30. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  31. public void Return(T item) => objects.Push(item);
  32. // count to see how many objects are in the pool. useful for tests.
  33. public int Count => objects.Count;
  34. }
  35. }