Created
March 17, 2019 05:48
-
-
Save electricessence/0101961626d9026ded220ef41dbdaab3 to your computer and use it in GitHub Desktop.
LocalArrayPool<T> and Extensions
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
static class LocalArrayPool<T> | |
{ | |
public const int MaxArrayLength = 1024 * 1024; | |
static LocalArrayPool() | |
{ | |
Instance = ArrayPool<T>.Create(MaxArrayLength, 4); | |
} | |
public static readonly ArrayPool<T> Instance; | |
public static void Rent( | |
int minimumLength, | |
Action<Memory<T>> handler) | |
{ | |
if (minimumLength < 0) | |
throw new ArgumentOutOfRangeException(nameof(minimumLength), minimumLength, "Must be at least 0."); | |
if (minimumLength > MaxArrayLength) | |
{ | |
handler(new T[minimumLength]); | |
} | |
else | |
{ | |
var array = Instance.Rent(minimumLength); | |
try | |
{ | |
handler(new Memory<T>(array, 0, minimumLength)); | |
} | |
finally | |
{ | |
Instance.Return(array, false); | |
} | |
} | |
} | |
public static TResult Rent<TResult>( | |
long minimumLength, | |
bool clearAfter, | |
Func<Memory<T>, TResult> handler) | |
{ | |
if (minimumLength < 0) | |
throw new ArgumentOutOfRangeException(nameof(minimumLength), minimumLength, "Must be at least 0."); | |
if (minimumLength > MaxArrayLength) | |
{ | |
return handler(new T[minimumLength]); | |
} | |
else | |
{ | |
var array = Instance.Rent((int)(minimumLength)); | |
try | |
{ | |
return handler(array); | |
} | |
finally | |
{ | |
Instance.Return(array, clearAfter); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment