🎓 A1Learner
🔍
0 of 28 lessons completed

C# Memory and stackalloc

Memory<T> is a storable handle to a block of memory. stackalloc reserves a small block on the stack, and a Span<T> gives code a short-lived view of either block.

stackalloc into a Span

The block holds four ints on the stack. A loop fills it with squares and a second loop prints them.

using System;

class Program
{
    static void Main(string[] args)
    {
        Span<int> numbers = stackalloc int[4];
        for (int i = 0; i < numbers.Length; i++)
        {
            numbers[i] = (i + 1) * (i + 1);
        }
        for (int i = 0; i < numbers.Length; i++)
        {
            Console.WriteLine(numbers[i]);
        }
    }
}

Memory stored in a field

The Box class stores a Memory<int> in a field. Fill writes through the Span view and Total adds the values.

using System;

class Box
{
    public Memory<int> Data;

    public Box(int size)
    {
        Data = new int[size];
    }

    public void Fill()
    {
        Span<int> span = Data.Span;
        span[0] = 1;
        span[1] = 2;
        span[2] = 3;
    }

    public int Total()
    {
        Span<int> span = Data.Span;
        int total = 0;
        for (int i = 0; i < span.Length; i++)
        {
            total += span[i];
        }
        return total;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Box box = new Box(3);
        box.Fill();
        Console.WriteLine(box.Total());
    }
}

Slicing a Memory

Slice picks out the middle two values of the stored block. The sum covers only that part.

using System;

class Box
{
    public Memory<int> Data = new int[] { 10, 20, 30, 40 };
}

class Program
{
    static void Main(string[] args)
    {
        Box box = new Box();
        Memory<int> part = box.Data.Slice(1, 2);
        Span<int> span = part.Span;
        int total = 0;
        for (int i = 0; i < span.Length; i++)
        {
            total += span[i];
        }
        Console.WriteLine(total);
    }
}

Example

using System;

class Program
{
    static void Main(string[] args)
    {
        Span<char> letters = stackalloc char[3];
        letters[0] = 'a';
        letters[1] = 'b';
        letters[2] = 'c';
        Console.WriteLine(new string(letters));
    }
}

Key points

  • stackalloc creates an array on the stack instead of the heap.
  • A stackalloc block is usually handed straight to a Span<T>.
  • The stack block is freed when the method returns.
  • A Span<T> cannot be stored in a field of a class.
  • Memory<T> can be stored in a field, because it is a regular object.
  • The Span property of a Memory<T> gives a short-lived view for reading and writing.
  • Slice on a Memory<T> returns a smaller Memory<T> over part of the same block.

In this example, stackalloc reserves room for three chars on the stack. The code stores one letter in each slot. new string copies the span into a string, and the line prints abc.

Note

stackalloc suits small, short-lived buffers, because the stack space is limited.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Why does a class store a Memory<T> instead of a Span<T> in a field?