-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathObjectPool.cs
More file actions
164 lines (147 loc) · 5.74 KB
/
ObjectPool.cs
File metadata and controls
164 lines (147 loc) · 5.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// Ported from Roslyn, see: https://github.com/dotnet/roslyn/blob/main/src/Dependencies/PooledObjects/ObjectPool%601.cs.
using System;
using System.Runtime.CompilerServices;
using System.Threading;
namespace ZBase.Foundation.SourceGen
{
/// <summary>
/// <para>
/// Generic implementation of object pooling pattern with predefined pool size limit. The main purpose
/// is that limited number of frequently used objects can be kept in the pool for further recycling.
/// </para>
/// <para>
/// Notes:
/// <list type="number">
/// <item>
/// It is not the goal to keep all returned objects. Pool is not meant for storage. If there
/// is no space in the pool, extra returned objects will be dropped.
/// </item>
/// <item>
/// It is implied that if object was obtained from a pool, the caller will return it back in
/// a relatively short time. Keeping checked out objects for long durations is ok, but
/// reduces usefulness of pooling. Just new up your own.
/// </item>
/// </list>
/// </para>
/// <para>
/// Not returning objects to the pool in not detrimental to the pool's work, but is a bad practice.
/// Rationale: if there is no intent for reusing the object, do not use pool - just use "new".
/// </para>
/// </summary>
/// <typeparam name="T">The type of objects to pool.</typeparam>
public sealed class ObjectPool<T>
where T : class
{
/// <summary>
/// The factory is stored for the lifetime of the pool. We will call this only when pool needs to
/// expand. compared to "new T()", Func gives more flexibility to implementers and faster than "new T()".
/// </summary>
private readonly Func<T> _factory;
/// <summary>
/// The array of cached items.
/// </summary>
private readonly Element[] _items;
/// <summary>
/// Storage for the pool objects. The first item is stored in a dedicated field
/// because we expect to be able to satisfy most requests from it.
/// </summary>
private T _firstItem;
/// <summary>
/// Creates a new <see cref="ObjectPool{T}"/> instance with the specified parameters.
/// </summary>
/// <param name="factory">The input factory to produce <typeparamref name="T"/> items.</param>
public ObjectPool(Func<T> factory)
: this(factory, Environment.ProcessorCount * 2)
{
}
/// <summary>
/// Creates a new <see cref="ObjectPool{T}"/> instance with the specified parameters.
/// </summary>
/// <param name="factory">The input factory to produce <typeparamref name="T"/> items.</param>
/// <param name="size">The pool size to use.</param>
public ObjectPool(Func<T> factory, int size)
{
this._factory = factory;
this._items = new Element[size - 1];
}
/// <summary>
/// Produces a <typeparamref name="T"/> instance.
/// </summary>
/// <returns>The returned <typeparamref name="T"/> item to use.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Allocate()
{
T item = this._firstItem;
if (item is null || item != Interlocked.CompareExchange(ref this._firstItem, null, item))
{
item = AllocateSlow();
}
return item;
}
/// <summary>
/// Returns a given <typeparamref name="T"/> instance to the pool.
/// </summary>
/// <param name="obj">The <typeparamref name="T"/> instance to return.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Free(T obj)
{
if (this._firstItem is null)
{
this._firstItem = obj;
}
else
{
FreeSlow(obj);
}
}
/// <summary>
/// Allocates a new <typeparamref name="T"/> item.
/// </summary>
/// <returns>The returned <typeparamref name="T"/> item to use.</returns>
[MethodImpl(MethodImplOptions.NoInlining)]
private T AllocateSlow()
{
foreach (ref Element element in this._items.AsSpan())
{
T instance = element._value;
if (instance is not null)
{
if (instance == Interlocked.CompareExchange(ref element._value, null, instance))
{
return instance;
}
}
}
return this._factory();
}
/// <summary>
/// Frees a given <typeparamref name="T"/> item.
/// </summary>
/// <param name="obj">The <typeparamref name="T"/> item to return to the pool.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void FreeSlow(T obj)
{
foreach (ref Element element in this._items.AsSpan())
{
if (element._value is null)
{
element._value = obj;
break;
}
}
}
/// <summary>
/// A container for a produced item (using a <see langword="struct"/> wrapper to avoid covariance checks).
/// </summary>
private struct Element
{
/// <summary>
/// The value held at the current element.
/// </summary>
internal T _value;
}
}
}