Advertisement
Advanced C#, Arrays, Span<T> & Memory<T>

How does 'stackalloc' work together with Span<T> to allocate memory on the stack instead of the heap?

Short answer

'stackalloc' allocates a block of memory directly on the CURRENT STACK FRAME (not the garbage-collected heap), and assigning it to a Span gives you safe, bounds-checked access to that memory — ideal for small, short-lived buffers in performance-critical code, completely avoiding…

Save C# mock interview
Advertisement
AModel answer
'stackalloc' allocates a block of memory directly on the CURRENT STACK FRAME (not the garbage-collected heap), and assigning it to a Span<T> gives you safe, bounds-checked access to that memory — ideal for small, short-lived buffers in performance-critical code, completely avoiding GC pressure, but the memory is only valid for the lifetime of the current method call.
Span<int> buffer = stackalloc int[100]; // allocated on the stack, zero GC pressure
for (int i = 0; i < buffer.Length; i++) {
  buffer[i] = i * i;
}
Real-world example
Building a small, fixed-size scratch buffer for a hot-path numeric algorithm, avoiding heap allocation entirely.
Likely follow-ups
  • What happens if you try to stackalloc a very large amount of memory, like 1MB?
Related topics