You are writing a method and you create a new list. This list will be allocated on the heap and most times you know the length of this list. So today, I ‘ll teach you how to make your code faster with one very simple word, stackalloc.

What is stackalloc?

The stackalloc keyword in C# is used to allocate a block of memory on the stack rather than the heap. This means the memory is automatically released when the method that called stackalloc returns, eliminating the overhead associated with garbage collection. Stack allocation is faster and can lead to performance improvements in scenarios where memory is allocated and deallocated frequently.

How to Use stackalloc

Before C# 7.2, using stackalloc required working with pointers in an unsafe context. With the introduction of Span<T>, you can now use stackalloc in safe code without dealing with pointers:

Span<int> numbers = stackalloc int[100];
for (int i = 0; i < numbers.Length; i++)
{
    numbers[i] = i;
}

Let’s run a benchmark as well to see the allocations:

[MemoryDiagnoser]
public class StackallocVsList
{
    [Benchmark]
    public void Stackalloc()
    {
        Span<int> span = stackalloc int[100];
        for (int i = 0; i < span.Length; i++)
        {
            span[i] = i;
        }
    }

    [Benchmark]
    public void List()
    {
        List<int> list = new(100);
        for (int i = 0; i < list.Capacity; i++)
        {
            list.Add(i);
        }
    }
}
MethodMeanErrorStdDevGen0Allocated
Stackalloc28.24 ns0.160 ns0.142 ns
List109.26 ns1.618 ns1.435 ns0.0545456 B

So we got zero memory allocations!

Why Use stackalloc?

  • Performance Gains: Allocating memory on the stack is generally faster than on the heap because it involves simple pointer arithmetic rather than complex heap management.
  • Reduced Garbage Collection Pressure: By avoiding heap allocations, you decrease the workload on the garbage collector, which can improve application responsiveness.

Limitations and Considerations

  • Stack Size Limitations: The default stack size is limited. Allocating large amounts of memory on the stack can create StackOverflowExceptions.
  • Scope and Lifetime: The memory allocated with stackalloc is only valid within the method where it was allocated. Do not return references to this memory.
  • No Dynamic Sizing: The size of the allocated memory must be known at compile time or determined by a local variable at runtime, but it cannot be a field or property.
  • Platform Compatibility: While stackalloc is widely supported, certain platforms or runtime environments may have different stack size limitations.

Conclusion

The stackalloc keyword is a valuable tool for developers looking to optimize memory allocation and improve application performance in .NET. By allocating memory on the stack, you can reduce heap fragmentation and minimize garbage collection overhead. However, it’s essential to use stackalloc carefully, keeping in mind the limitations and potential risks associated with stack memory allocation.

Affiliate promo

If you love learning new stuff and want to support me, consider buying a course from Dometrain using this link: Browse courses – Dometrain. Thank you!

Leave a comment

Trending