May 22

Arrays in .NET– part VI

Posted in .NET Basics C#      Comments Off on Arrays in .NET– part VI

I’ve ended the previous post saying that there was still one extra mile we could take to improve the performance associated with arrays in .NET. This extra mile has a name: stackalloc. The stackalloc keyword can only be used in unsafe code and it’s responsible for allocating a block of memory on the stack. In practice, stackalloc creates a single-dimension zero-based array of of value type elements (whose fields’ types are not allowed to be reference types).

There are a couple of things you should keep in mind if you decide to use this option:

  • since the memory block is allocated in the stack, then that memory will automatically be reclaimed at the end of the method where it was allocated.
  • you won’t be able to pass this memory block to most of the  methods exposed by the types introduced by the framework.

Having said this, it’s time to show a quick sample:

unsafe {
    //allocate array in the stack
    //big enough for 10 ints
    Int32* ints = stackalloc Int32[10];
    //fill it with 10 ints
    for (var i = 0; i < 10; i++) {
        ints[i] = i;
    //now do something with ints
    //probably pass it along
    for (var i = 0; i < 10; i++) {

As you can see, it’s not that complicated. The stackalloc keyword is used in place of the new keyword and we end up with a memory block in the stack which is big enough for storing 10 integers.

In the real world, you’ll (probably) use the stackalloc keyword for those scenarios where performance is a must or when you need to use interop to communicate with unmanaged code. In fact, I think that interop is one of those scenarios where stackalloc is a good option.  By using it, you don’t have to allocate an array in the heap (leading to less GC pressure), you don’t have to pin memory (don’t forget that this is a must for passing a reference from a managed object to unmanaged code) and you get automatic clean up on the method’s exit.

Since we’re talking about arrays allocated in the stack, there’s still one more option: fixed size buffers. We’ll take a look at them in the next post! And that’s it for now. Stay tuned for more.