Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would I need to use the stackalloc keyword in C#?

What functionality does the stackalloc keyword provide? When and Why would I want to use it?

like image 660
PaulB Avatar asked Apr 06 '09 12:04

PaulB


People also ask

When should I use Stackalloc?

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.

What is Alloca?

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).


2 Answers

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.

like image 96
Steve Avatar answered Oct 11 '22 19:10

Steve


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. } 
like image 28
Aaron Schultz Avatar answered Oct 11 '22 19:10

Aaron Schultz