Pool.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System.Text;
  2. using System.Collections.Generic;
  3. namespace WXB
  4. {
  5. internal class PoolData<T> where T : new()
  6. {
  7. static public List<T> bufs = new List<T>();
  8. static public T Get()
  9. {
  10. if (bufs.Count == 0)
  11. {
  12. return new T();
  13. }
  14. T t = bufs[bufs.Count - 1];
  15. bufs.RemoveAt(bufs.Count - 1);
  16. return t;
  17. }
  18. static public void Free(T t)
  19. {
  20. bufs.Add(t);
  21. }
  22. static public void FreeList(List<T> list, System.Action<T> fun)
  23. {
  24. for (int i = 0; i < list.Count; ++i)
  25. fun(list[i]);
  26. bufs.AddRange(list);
  27. list.Clear();
  28. }
  29. }
  30. internal struct PD<T> : System.IDisposable where T : new()
  31. {
  32. public PD(System.Action<T> free)
  33. {
  34. value = PoolData<T>.Get();
  35. this.free = free;
  36. }
  37. public T value;
  38. private System.Action<T> free;
  39. public void Dispose()
  40. {
  41. free(value);
  42. PoolData<T>.Free(value);
  43. }
  44. }
  45. interface IFactory
  46. {
  47. object create();
  48. }
  49. internal class Factory<T> : IFactory where T : new()
  50. {
  51. public Factory(System.Action<T> f)
  52. {
  53. free = f;
  54. }
  55. public System.Action<T> free;
  56. public object create()
  57. {
  58. return new PD<T>(free);
  59. }
  60. }
  61. internal static class Pool
  62. {
  63. static Factory<StringBuilder> sb_factory = null;
  64. public static PD<StringBuilder> GetSB()
  65. {
  66. if (sb_factory == null)
  67. {
  68. sb_factory = new Factory<StringBuilder>((StringBuilder sb) => { sb.Length = 0; });
  69. }
  70. return (PD<StringBuilder>)sb_factory.create();
  71. }
  72. }
  73. }