Adding to the existing answer:
Remember, using ArrayPool
instead of allocating with new
puts the responsibility of freeing the memory on you. Your application will not leak memory if you don't guarantee that the Return method is called, but the ArrayPool
is prevented from reusing the memory, thus denying the benefits you gain from using ArrayPool
.
In simple use cases where you create a buffer and release it in the same method, it makes sense to put it into a finally clause:
private static void LocalUseOfSharedPool(int i)
{
int[] arr = ArrayPool<int>.Shared.Rent(ARRAYSIZE);
try
{
ShowAddress($"simple array {i}", arr);
FillTheArray(arr);
UseTheArray(arr);
}
finally
{
ArrayPool<int>.Shared.Return(arr);
}
}
In more complex cases you must make sure to not leak the memory in other ways.
Also note, that your buffer now has a lifetime. If you pass your array to another object B
, you need to make sure, that object B
is not using the array after your call to ArrayPool<>.Return
.
Since using ArrayPool
is a performance issue, measure the gains of using it, especially if you want to change an existing system.