Pool.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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. // stack increases the chance that a reused writer remains in cache.
  12. readonly Stack<T> objects = new Stack<T>();
  13. // some types might need additional parameters in their constructor, so
  14. // we use a Func<T> generator
  15. readonly Func<T> objectGenerator;
  16. public Pool(Func<T> objectGenerator, int initialCapacity)
  17. {
  18. this.objectGenerator = objectGenerator;
  19. // allocate an initial pool so we have fewer (if any)
  20. // allocations in the first few frames (or seconds).
  21. for (int i = 0; i < initialCapacity; ++i)
  22. objects.Push(objectGenerator());
  23. }
  24. // take an element from the pool, or create a new one if empty
  25. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  26. public T Get() => objects.Count > 0 ? objects.Pop() : objectGenerator();
  27. // return an element to the pool
  28. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  29. public void Return(T item) => objects.Push(item);
  30. // count to see how many objects are in the pool. useful for tests.
  31. public int Count => objects.Count;
  32. }
  33. }