What functionality does the stackalloc
keyword provide? When and Why would I want to use it?
stackalloc is desirable in some performance sensitive areas. It can be used in places where small arrays were used, with the advantage that it does not allocate on the heap - and thus does not apply pressure to the garbage collector. stackalloc is not a general purpose drop-in for arrays.
The alloca() function is machine- and compiler-dependent. For certain applications, its use can improve efficiency compared to the use of malloc(3) plus free(3). In certain cases, it can also simplify memory deallocation in applications that use longjmp(3) or siglongjmp(3).
From MSDN:
Used in an unsafe code context to allocate a block of memory on the stack.
One of the main features of C# is that you do not normally need to access memory directly, as you would do in C/C++ using malloc
or new
. However, if you really want to explicitly allocate some memory you can, but C# considers this "unsafe", so you can only do it if you compile with the unsafe
setting. stackalloc
allows you to allocate such memory.
You almost certainly don't need to use it for writing managed code. It is feasible that in some cases you could write faster code if you access memory directly - it basically allows you to use pointer manipulation which suits some problems. Unless you have a specific problem and unsafe code is the only solution then you will probably never need this.
Stackalloc will allocate data on the stack, which can be used to avoid the garbage that would be generated by repeatedly creating and destroying arrays of value types within a method.
public unsafe void DoSomeStuff() { byte* unmanaged = stackalloc byte[100]; byte[] managed = new byte[100]; //Do stuff with the arrays //When this method exits, the unmanaged array gets immediately destroyed. //The managed array no longer has any handles to it, so it will get //cleaned up the next time the garbage collector runs. //In the mean-time, it is still consuming memory and adding to the list of crap //the garbage collector needs to keep track of. If you're doing XNA dev on the //Xbox 360, this can be especially bad. }
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