The sole reason to use stackalloc
is performance (either for computations or interop). By using stackalloc
instead of a heap allocated array, you create less GC pressure (the GC needs to run less), you don’t need to pin the arrays down, it’s faster to allocate than a heap array, an it is automatically freed on method exit (heap allocated arrays are only deallocated when GC runs). Also by using stackalloc
instead of a native allocator (like malloc or the .Net equivalent) you also gain speed and automatic deallocation on scope exit.
Performance wise, if you use stackalloc
you greatly increase the chance of cache hits on the CPU due to the locality of data.