I was reading the official ASP.NET Core Performance Best Practices documentation on Microsoft Website.
In order to increase performance, they recommend to use ArrayPool to store large array.
But, what is ArrayPool and how does that work ? Looking on internet and official documentation didn't help me to understand how it works and in which scenario I should use it.
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.
We are looking to switch to arraypool because we allocate very large arrays in order to respond to http requests and we were running out of "free" memory in the process which was causing memory allocation delays upwards of 10+ seconds randomly.
For full details, see this post: Is correct to use GC.Collect(); GC.WaitForPendingFinalizers();?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With