Pool.cs 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. // pool to avoid allocations. originally from libuv2k.
  2. using System;
  3. using System.Collections.Generic;
  4. namespace Telepathy
  5. {
  6. public class Pool<T>
  7. {
  8. // objects
  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. // constructor
  14. public Pool(Func<T> objectGenerator)
  15. {
  16. this.objectGenerator = objectGenerator;
  17. }
  18. // take an element from the pool, or create a new one if empty
  19. public T Take() => objects.Count > 0 ? objects.Pop() : objectGenerator();
  20. // return an element to the pool
  21. public void Return(T item) => objects.Push(item);
  22. // clear the pool with the disposer function applied to each object
  23. public void Clear() => objects.Clear();
  24. // count to see how many objects are in the pool. useful for tests.
  25. public int Count() => objects.Count;
  26. }
  27. }