Created
October 10, 2024 21:57
-
-
Save jvyden/83ecb2dbeb479ab3ed24013dfd3c3755 to your computer and use it in GitHub Desktop.
An array pool that returns the exact array size requested. I never ended up using this but I'd like to keep this somewhere.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ExactArrayPool<T> : ArrayPool<T> | |
{ | |
public static ArrayPool<T> Shared { get; } = new ExactArrayPool<T>(); | |
private readonly Dictionary<int, Queue<T[]>> _pools = new Dictionary<int, Queue<T[]>>(); | |
[Pure] | |
private Queue<T[]> GetOrCreatePool(int minimumLength) | |
{ | |
if (this._pools.TryGetValue(minimumLength, out Queue<T[]> pool)) | |
return pool; | |
pool = new Queue<T[]>(); | |
this._pools.Add(minimumLength, pool); | |
return pool; | |
} | |
public override T[] Rent(int minimumLength) | |
{ | |
Queue<T[]> pool = GetOrCreatePool(minimumLength); | |
if (pool.TryDequeue(out T[] array)) | |
return array; | |
return new T[minimumLength]; | |
} | |
public override void Return(T[] array, bool clearArray = false) | |
{ | |
if (clearArray) | |
{ | |
for (int i = 0; i < array.Length; i++) | |
{ | |
array[i] = default; | |
} | |
} | |
Queue<T[]> pool = GetOrCreatePool(array.Length); | |
pool.Enqueue(array); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment