|
| 1 | +using System.Diagnostics; |
| 2 | + |
| 3 | +namespace CSharpier.Utilities; |
| 4 | + |
| 5 | +// From https://github.com/dotnet/roslyn/blob/38f239fb81b72bfd313cd18aeff0b0ed40f34c5c/src/Dependencies/PooledObjects/ObjectPool%601.cs#L42 |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// Generic implementation of object pooling pattern with predefined pool size limit. The main |
| 9 | +/// purpose is that limited number of frequently used objects can be kept in the pool for |
| 10 | +/// further recycling. |
| 11 | +/// |
| 12 | +/// Notes: |
| 13 | +/// 1) it is not the goal to keep all returned objects. Pool is not meant for storage. If there |
| 14 | +/// is no space in the pool, extra returned objects will be dropped. |
| 15 | +/// |
| 16 | +/// 2) it is implied that if object was obtained from a pool, the caller will return it back in |
| 17 | +/// a relatively short time. Keeping checked out objects for long durations is ok, but |
| 18 | +/// reduces usefulness of pooling. Just new up your own. |
| 19 | +/// |
| 20 | +/// Not returning objects to the pool in not detrimental to the pool's work, but is a bad practice. |
| 21 | +/// Rationale: |
| 22 | +/// If there is no intent for reusing the object, do not use pool - just use "new". |
| 23 | +/// </summary> |
| 24 | +internal class ObjectPool<T> |
| 25 | + where T : class |
| 26 | +{ |
| 27 | + [DebuggerDisplay("{Value,nq}")] |
| 28 | + private struct Element |
| 29 | + { |
| 30 | + internal T? Value; |
| 31 | + } |
| 32 | + |
| 33 | + /// <remarks> |
| 34 | + /// Not using System.Func{T} because this file is linked into the (debugger) Formatter, |
| 35 | + /// which does not have that type (since it compiles against .NET 2.0). |
| 36 | + /// </remarks> |
| 37 | + internal delegate T Factory(); |
| 38 | + |
| 39 | + // Storage for the pool objects. The first item is stored in a dedicated field because we |
| 40 | + // expect to be able to satisfy most requests from it. |
| 41 | + private T? _firstItem; |
| 42 | + private readonly Element[] _items; |
| 43 | + |
| 44 | + // factory is stored for the lifetime of the pool. We will call this only when pool needs to |
| 45 | + // expand. compared to "new T()", Func gives more flexibility to implementers and faster |
| 46 | + // than "new T()". |
| 47 | + private readonly Factory _factory; |
| 48 | + |
| 49 | + public readonly bool TrimOnFree; |
| 50 | + |
| 51 | + internal ObjectPool(Factory factory, bool trimOnFree = true) |
| 52 | + : this(factory, Environment.ProcessorCount * 2, trimOnFree) { } |
| 53 | + |
| 54 | + internal ObjectPool(Factory factory, int size, bool trimOnFree = true) |
| 55 | + { |
| 56 | + Debug.Assert(size >= 1); |
| 57 | + _factory = factory; |
| 58 | + _items = new Element[size - 1]; |
| 59 | + TrimOnFree = trimOnFree; |
| 60 | + } |
| 61 | + |
| 62 | + internal ObjectPool(Func<ObjectPool<T>, T> factory, int size) |
| 63 | + { |
| 64 | + Debug.Assert(size >= 1); |
| 65 | + _factory = () => factory(this); |
| 66 | + _items = new Element[size - 1]; |
| 67 | + } |
| 68 | + |
| 69 | + private T CreateInstance() |
| 70 | + { |
| 71 | + var inst = _factory(); |
| 72 | + return inst; |
| 73 | + } |
| 74 | + |
| 75 | + /// <summary> |
| 76 | + /// Produces an instance. |
| 77 | + /// </summary> |
| 78 | + /// <remarks> |
| 79 | + /// Search strategy is a simple linear probing which is chosen for it cache-friendliness. |
| 80 | + /// Note that Free will try to store recycled objects close to the start thus statistically |
| 81 | + /// reducing how far we will typically search. |
| 82 | + /// </remarks> |
| 83 | + internal T Allocate() |
| 84 | + { |
| 85 | + // PERF: Examine the first element. If that fails, AllocateSlow will look at the remaining elements. |
| 86 | + // Note that the initial read is optimistically not synchronized. That is intentional. |
| 87 | + // We will interlock only when we have a candidate. in a worst case we may miss some |
| 88 | + // recently returned objects. Not a big deal. |
| 89 | + var inst = _firstItem; |
| 90 | + if (inst == null || inst != Interlocked.CompareExchange(ref _firstItem, null, inst)) |
| 91 | + { |
| 92 | + inst = AllocateSlow(); |
| 93 | + } |
| 94 | + |
| 95 | + return inst; |
| 96 | + } |
| 97 | + |
| 98 | + private T AllocateSlow() |
| 99 | + { |
| 100 | + var items = _items; |
| 101 | + |
| 102 | + for (var i = 0; i < items.Length; i++) |
| 103 | + { |
| 104 | + // Note that the initial read is optimistically not synchronized. That is intentional. |
| 105 | + // We will interlock only when we have a candidate. in a worst case we may miss some |
| 106 | + // recently returned objects. Not a big deal. |
| 107 | + var inst = items[i].Value; |
| 108 | + if (inst != null) |
| 109 | + { |
| 110 | + if (inst == Interlocked.CompareExchange(ref items[i].Value, null, inst)) |
| 111 | + { |
| 112 | + return inst; |
| 113 | + } |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + return CreateInstance(); |
| 118 | + } |
| 119 | + |
| 120 | + /// <summary> |
| 121 | + /// Returns objects to the pool. |
| 122 | + /// </summary> |
| 123 | + /// <remarks> |
| 124 | + /// Search strategy is a simple linear probing which is chosen for it cache-friendliness. |
| 125 | + /// Note that Free will try to store recycled objects close to the start thus statistically |
| 126 | + /// reducing how far we will typically search in Allocate. |
| 127 | + /// </remarks> |
| 128 | + internal void Free(T obj) |
| 129 | + { |
| 130 | + Validate(obj); |
| 131 | + |
| 132 | + if (_firstItem == null) |
| 133 | + { |
| 134 | + // Intentionally not using interlocked here. |
| 135 | + // In a worst case scenario two objects may be stored into same slot. |
| 136 | + // It is very unlikely to happen and will only mean that one of the objects will get collected. |
| 137 | + _firstItem = obj; |
| 138 | + } |
| 139 | + else |
| 140 | + { |
| 141 | + FreeSlow(obj); |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + private void FreeSlow(T obj) |
| 146 | + { |
| 147 | + var items = _items; |
| 148 | + for (var i = 0; i < items.Length; i++) |
| 149 | + { |
| 150 | + if (items[i].Value == null) |
| 151 | + { |
| 152 | + // Intentionally not using interlocked here. |
| 153 | + // In a worst case scenario two objects may be stored into same slot. |
| 154 | + // It is very unlikely to happen and will only mean that one of the objects will get collected. |
| 155 | + items[i].Value = obj; |
| 156 | + break; |
| 157 | + } |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + private void Validate(object obj) |
| 162 | + { |
| 163 | + Debug.Assert(obj != null, "freeing null?"); |
| 164 | + |
| 165 | + Debug.Assert(_firstItem != obj, "freeing twice?"); |
| 166 | + |
| 167 | + var items = _items; |
| 168 | + for (var i = 0; i < items.Length; i++) |
| 169 | + { |
| 170 | + var value = items[i].Value; |
| 171 | + if (value == null) |
| 172 | + { |
| 173 | + return; |
| 174 | + } |
| 175 | + |
| 176 | + Debug.Assert(value != obj, "freeing twice?"); |
| 177 | + } |
| 178 | + } |
| 179 | +} |
0 commit comments