Pool.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. // Pool to avoid allocations (from libuv2k)
  2. using System;
  3. using System.Collections.Generic;
  4. namespace Mirror
  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. public Pool(Func<T> objectGenerator, int initialCapacity)
  14. {
  15. this.objectGenerator = objectGenerator;
  16. // allocate an initial pool so we have fewer (if any)
  17. // allocations in the first few frames (or seconds).
  18. for (int i = 0; i < initialCapacity; ++i)
  19. objects.Push(objectGenerator());
  20. }
  21. // take an element from the pool, or create a new one if empty
  22. public T Take() => objects.Count > 0 ? objects.Pop() : objectGenerator();
  23. // return an element to the pool
  24. public void Return(T item) => objects.Push(item);
  25. // count to see how many objects are in the pool. useful for tests.
  26. public int Count => objects.Count;
  27. }
  28. }