What is stackalloc in C# and How to Use It
stackalloc in C# is a keyword that allocates a block of memory on the stack instead of the heap. It is used for fast, temporary memory allocation, typically for small arrays, and the memory is automatically freed when the method ends.How It Works
Imagine you have a small notebook (the stack) and a big filing cabinet (the heap). When you use stackalloc, you quickly grab some pages from the notebook to write temporary notes. These pages are very fast to access and automatically cleared when you finish your work.
In C#, stackalloc allocates memory directly on the stack, which is a special area of memory that stores temporary data for methods. This memory is very fast to allocate and free because it works like a stack of plates: you add or remove plates only from the top.
This is different from normal memory allocation on the heap, which is slower and requires garbage collection to clean up. Using stackalloc is useful when you need quick, short-lived memory without the overhead of the heap.
Example
This example shows how to use stackalloc to create a small array of integers on the stack and sum its values.
using System; class Program { static void Main() { Span<int> numbers = stackalloc int[] { 1, 2, 3, 4, 5 }; int sum = 0; foreach (var num in numbers) { sum += num; } Console.WriteLine($"Sum: {sum}"); } }
When to Use
Use stackalloc when you need a small, temporary array or buffer that lives only within a method and you want to avoid the overhead of heap allocation. It is ideal for performance-critical code like parsing, graphics, or low-level data processing.
However, because the stack size is limited, stackalloc should only be used for small allocations. Large allocations can cause a stack overflow error. Also, stackalloc works well with Span<T> to safely handle stack memory.
Key Points
stackallocallocates memory on the stack, which is fast and temporary.- Memory allocated with
stackallocis automatically freed when the method ends. - It is best for small arrays or buffers to improve performance.
- Works well with
Span<T>for safe memory access. - Not suitable for large allocations due to limited stack size.
Key Takeaways
stackalloc allocates fast, temporary memory on the stack.Span<T> for safe and efficient access.