SkipInitLocal or ArrayPool
03/05/2022
Many data processing algorithms require a temporary data storage for certain operations. I have been recently working with one such algorithm in the sound processing domain. In my case a fixed sized temporary byte array has been required for a method execution. In a performance sensitive code, one would prefer to achieve a non-allocating solution for this problem.
In the particular case it was a tight loop for processing live sound data. Allocating a new array for every iteration of the loop is excessive. However, I could also not use a pre-allocated array for the purpose, due to the structure of the code. There are still a few options to acquire a temporary array:
using an ArrayPool
allocating on the stack with stackalloc
ArrayPool
type provides a shared pool of arrays, from which a developer might rent an array, and return it once it is no longer needed. This array exists on the heap as a regular array, and the ArrayPool
makes sure to provide an array when renting which is at least the size asked for. Because the array is returned to the pool after usage, the next iteration of the algorithm may re-use the same array, avoiding any excess allocation.