ObjectPool.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // RichTextKit
  2. // Copyright © 2019-2020 Topten Software. All Rights Reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. // not use this product except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. //#define NO_POOLING
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Text;
  19. namespace Topten.RichTextKit.Utils
  20. {
  21. internal class ObjectPool<T> where T : class, new()
  22. {
  23. public ObjectPool()
  24. {
  25. }
  26. public T Get()
  27. {
  28. #if NO_POOLING
  29. return new T();
  30. #else
  31. int count = _pool.Count;
  32. if (count == 0)
  33. return new T();
  34. var obj = _pool[count - 1];
  35. _pool.RemoveAt(count - 1);
  36. return obj;
  37. #endif
  38. }
  39. public void Return(T obj)
  40. {
  41. #if NO_POOLING
  42. #else
  43. Cleaner?.Invoke(obj);
  44. _pool.Add(obj);
  45. #endif
  46. }
  47. public void Return(IEnumerable<T> objs)
  48. {
  49. #if NO_POOLING
  50. #else
  51. if (Cleaner != null)
  52. {
  53. foreach (var x in objs)
  54. {
  55. Cleaner(x);
  56. }
  57. _pool.AddRange(objs);
  58. }
  59. #endif
  60. }
  61. public void ReturnAndClear(List<T> objs)
  62. {
  63. #if NO_POOLING
  64. #else
  65. if (Cleaner != null)
  66. {
  67. foreach (var x in objs)
  68. {
  69. Cleaner(x);
  70. }
  71. _pool.AddRange(objs);
  72. }
  73. #endif
  74. objs.Clear();
  75. }
  76. public Action<T> Cleaner;
  77. List<T> _pool = new List<T>();
  78. }
  79. }