perf: improved pool return method by using a hashset for searching if the returning item is already queued
This commit is contained in:
@@ -10,22 +10,25 @@ public class Pool<T> : IPool<T>
|
||||
|
||||
private readonly Func<T> generator = null!;
|
||||
private readonly Queue<T> queue = new();
|
||||
private readonly HashSet<T> queuedHashes = [];
|
||||
|
||||
public T Get()
|
||||
{
|
||||
if (!queue.TryDequeue(out T? result))
|
||||
result = generator();
|
||||
|
||||
queuedHashes.Remove(result);
|
||||
OnRemoved?.Invoke(this, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
public void Return(T item)
|
||||
{
|
||||
if (queue.Contains(item))
|
||||
if (queuedHashes.Contains(item))
|
||||
return;
|
||||
|
||||
queue.Enqueue(item);
|
||||
queuedHashes.Add(item);
|
||||
OnReturned?.Invoke(this, item);
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user