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.


~ by Luis Abreu on May 22, 2011.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: