Pool.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Pool to avoid allocations (from libuv2k & Mirror)
  2. using System;
  3. using System.Collections.Generic;
  4. namespace kcp2k
  5. {
  6. public class Pool<T>
  7. {
  8. // Mirror is single threaded, no need for concurrent collections
  9. readonly Stack<T> objects = new Stack<T>();
  10. // some types might need additional parameters in their constructor, so
  11. // we use a Func<T> generator
  12. readonly Func<T> objectGenerator;
  13. // some types might need additional cleanup for returned objects
  14. readonly Action<T> objectResetter;
  15. public Pool(Func<T> objectGenerator, Action<T> objectResetter, int initialCapacity)
  16. {
  17. this.objectGenerator = objectGenerator;
  18. this.objectResetter = objectResetter;
  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. public T Take() => objects.Count > 0 ? objects.Pop() : objectGenerator();
  26. // return an element to the pool
  27. public void Return(T item)
  28. {
  29. objectResetter(item);
  30. objects.Push(item);
  31. }
  32. // clear the pool
  33. public void Clear() => objects.Clear();
  34. // count to see how many objects are in the pool. useful for tests.
  35. public int Count => objects.Count;
  36. }
  37. }