Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Using C# Span with Stackalloc for Zero-Allocation Buffers

Learn how to use C# Span<T> with stackalloc for zero-allocation temporary buffers: syntax, constraints, practical examples, and when to avoid stack allocation.

~9 min readC#
#Span<T>#stackalloc#memory management#performance
Iconic representation of a stack memory buffer with a C# Span pointer, symbolizing zero-allocation temporary buffers.

Temporary buffers are a common source of avoidable heap allocations. In C#, stackalloc combined with Span<T> lets you create a stack-based scratch buffer without allocating on the managed heap. This article covers the syntax, constraints, and practical scenarios for the technique.

When you need a temporary buffer inside a method and want to avoid allocating on the managed heap, stackalloc is a direct approach. The stackalloc keyword allocates memory on the current stack frame, and Span<T> provides a safe, bounds-checked view over that memory. This combination is useful in high-throughput code paths where repeated heap allocations would otherwise increase GC pressure.

Unlike an array, which lives on the heap and is garbage-collected, a stackalloc buffer is freed automatically when the method returns. This makes it attractive for short-lived scratch space. However, stack memory is limited, and a stackalloc buffer cannot outlive the method that creates it. A Span<T> created from stackalloc cannot be stored in a field, returned from a method, or carried across an await. These constraints shape where the technique is practical.

Basic Syntax: Stackalloc with Span

The simplest form uses the stackalloc expression directly in an assignment to a Span<T>:

csharp
Span<byte> buffer = stackalloc byte[256];

This allocates 256 bytes on the stack and creates a Span<byte> that points to that memory. The buffer is valid for the remainder of the current method. You do not need to explicitly free it; stack allocation is reclaimed when the method exits.

You can also initialize the buffer with values at creation:

csharp
Span<int> numbers = stackalloc int[] { 1, 2, 3, 4 };

The more common pattern is to fill it after allocation. The Span<T> indexer works the same as an array, so you can read and write elements. The runtime performs bounds checks, so accessing an index outside the buffer throws an IndexOutOfRangeException, just like an array.

Because Span<T> is a ref struct, it cannot be boxed, cannot be used as a field in a normal class or struct, and cannot be used in an async method. These restrictions prevent a stackalloc view from escaping the stack frame in which it was created.

When Stackalloc Makes Sense

Stackalloc is not a universal replacement for arrays. It is most useful when you need a small, temporary buffer and the allocation pattern would otherwise cause measurable GC pressure.

A typical example is formatting a number or processing a small transient dataset. For instance, if you repeatedly build a comma-separated list of integers, you can use a stackalloc buffer to avoid creating a new array on each call. The buffer lives on the stack, so it is allocated and released without involving the garbage collector.

A common guideline is to use stackalloc for small buffers, generally no more than a few hundred bytes, and to avoid large allocations. Default .NET stack space is often about 1 MB per thread, and it is shared with all method calls and local variables on that thread. Allocating a few megabytes on the stack can cause a StackOverflowException, which cannot be caught. A large buffer is better placed on the heap, either as a regular array or as an array rented from ArrayPool<T>.

Reading and Writing a Stackalloc Buffer with Span

Here is a practical method that uses Span<byte> with stackalloc to encode a simple binary header. It fills the buffer with a version number and a length field, then writes the bytes to a stream:

csharp
public static void WriteHeader(Stream stream, int version, int length) { Span<byte> header = stackalloc byte[12]; BitConverter.TryWriteBytes(header[0..4], version); BitConverter.TryWriteBytes(header[4..8], length); BitConverter.TryWriteBytes(header[8..12], 0); // reserved stream.Write(header); }

The stackalloc expression creates a stack-allocated buffer of 12 bytes. Slicing with ranges (header[0..4]) creates sub-spans that reference the same memory. Because the buffer is a Span<byte>, it can be passed directly to Stream.Write, which has an overload that accepts ReadOnlySpan<byte>. Some stream implementations can write directly from that span without copying, though you should not assume every stream is zero-allocating; the key benefit here is that no caller-owned array is created.

Note that BitConverter.TryWriteBytes writes the bytes in the platform's native endianness. That is a detail unrelated to stackalloc but essential when you rely on a particular binary layout.

Using Span<T> as a Method Parameter with Stackalloc Input

A common pattern is to pass a stackalloc-created Span<T> to a helper method. Since Span<T> is a ref struct, it can be passed as a parameter to a method that accepts Span<T> or ReadOnlySpan<T>. Here is an example of a helper that computes a simple checksum:

csharp
public static byte ComputeChecksum(ReadOnlySpan<byte> data) { byte sum = 0; foreach (byte b in data) { sum += b; } return sum; } public static byte CalculateChecksum(ReadOnlySpan<byte> payload) { Span<byte> fullData = stackalloc byte[payload.Length + 4]; payload.CopyTo(fullData); fullData[payload.Length] = 0; // padding fullData[payload.Length + 1] = 0; fullData[payload.Length + 2] = 0; fullData[payload.Length + 3] = 0; return ComputeChecksum(fullData); }

The helper ComputeChecksum accepts a ReadOnlySpan<byte> and iterates over it. The caller builds a larger stackalloc buffer and copies the input into it. This avoids heap allocation while still passing a unified span to the helper. The ReadOnlySpan<byte> parameter works for both array-based spans and stackalloc-based spans, so the helper is reusable across different allocation strategies.

Safety Constraints and Runtime Behavior

Several constraints govern the use of stackalloc with Span<T>.

Returning stackalloc Memory from a Method

You cannot return a stackalloc buffer from a method. The buffer exists in the method's stack frame and becomes invalid as soon as the method returns. The compiler rejects code that tries to return a Span<T> created with stackalloc. Returning a raw pointer to stackalloc memory has the same lifetime problem: the memory is invalid after the method returns, so it should never be returned to a caller.

If a method needs to fill a buffer, have the caller provide the destination span as a parameter:

csharp
public static void FillBuffer(Span<byte> destination) { destination[0] = 1; destination[1] = 2; }

Then the caller can use a stackalloc buffer as the argument.

Ref Struct Restrictions

Span<T> is a ref struct. That means it cannot be boxed, cannot be used as a field in a normal class or struct, cannot be captured by a lambda or closure, and cannot be used in an async method. This is deliberate: it prevents a span from outliving the memory it points to.

Stack Size Limits

Stack memory is finite. The default stack size for a .NET thread is often 1 MB, but that space is shared across the entire call chain. If you allocate many stackalloc buffers in deep recursion or large buffers per call, you risk a StackOverflowException. That exception is not catchable and will crash the process. Keep stackalloc sizes conservative.

A practical rule is to use stackalloc only for buffers up to a few hundred bytes. If you need more space, use a regular array or rent from ArrayPool<T>.

Combining stackalloc with Unsafe Code for More Control

stackalloc can also be used in an unsafe context to obtain a raw pointer. This is useful for interop scenarios where you need a pointer to a temporary buffer. For example:

csharp
public static void UseUnsafePointer(int length) { unsafe { int* buffer = stackalloc int[length]; for (int i = 0; i < length; i++) { buffer[i] = i * 2; } // Pass the pointer to an unmanaged function SomeNativeCall(buffer, length); } }

In this pattern, buffer is a raw pointer. You must declare an unsafe block and enable the /unsafe compiler option. This gives you direct memory access, but you lose bounds checking. You must be careful not to write beyond the allocated buffer. Prefer Span<T> when you do not need a pointer, because the compiler and runtime can help prevent buffer overruns.

Performance Considerations

The main performance benefit of stackalloc is eliminating heap allocation. Heap allocation itself is fast, but each allocation eventually contributes to garbage collection. In a tight loop that runs many times, avoiding even small allocations can reduce GC pressure and improve throughput.

However, stackalloc does not guarantee faster execution. Allocating on the stack is cheap, but the actual performance depends on what you do with the buffer. Operations that copy large amounts of data may still dominate. Do not use stackalloc just for the sake of it; measure where allocations matter.

In addition, Span<T> operations are often inlined by the JIT, so a stackalloc-backed span can compile to efficient code. The JIT may also optimize away bounds checks in some tight loops. No single benchmark number is useful here because results depend on workload, platform, and .NET version. The mechanism is clear: stackalloc avoids heap allocation and GC pressure, but it does not automatically make every algorithm faster.

Where Stackalloc with Span Tends to Fail or Mislead

Developers often try to use stackalloc in places that violate its constraints. The most frequent mistakes include:

  • Storing a Span<T> in a normal class or struct field, which is not allowed because Span<T> is a ref struct.
  • Passing a stackalloc span to an async method, which fails because the buffer cannot survive across an await.
  • Allocating a buffer that is too large, leading to StackOverflowException.
  • Using stackalloc in a recursive method with unbounded depth, which can exhaust stack space quickly.
  • Assuming that stackalloc is always faster than an array, which is not true when the array is short-lived and GC pressure is already low.

Another common trap is trying to capture a stackalloc-backed Span<T> in a logging delegate. Since Span<T> cannot be captured by a lambda, copy the relevant data out of the stack buffer before passing it to a delegate-based logging API.

Choosing Between stackalloc, ArrayPool, and Regular Arrays

The decision among these three allocation strategies depends on buffer size and lifetime.

StrategyBest ForLimitations
stackallocSmall, short-lived buffers (< ~1 KB)Cannot escape method, stack size limit
ArrayPool<T>Medium to large buffers reused across callsMust return rented array, pooling overhead
Regular arrayMost general useHeap allocation, GC pressure

Use stackalloc when the buffer is small and the method is hot. Use ArrayPool<T> when you need a buffer larger than a few hundred bytes and can return it after use. Use a regular array when simplicity matters and allocation pressure is not an issue.

A good rule of thumb: if you can allocate the buffer with a constant size that is safely below the stack limit, and you do not need to return it, stackalloc is a reasonable choice. If the buffer size is dynamic and can grow large, prefer ArrayPool<T>.

Advanced: Using stackalloc in a Loop Without Overflow

A subtle problem arises when you allocate a stackalloc buffer inside a loop. Each iteration can consume stack space until the method returns. If the loop runs many times and each iteration allocates a buffer, stack space may be exhausted even if each individual buffer is small.

Consider this pattern:

csharp
public static void ProcessInLoop(int iterations) { for (int i = 0; i < iterations; i++) { Span<byte> buffer = stackalloc byte[256]; // use buffer } }

Each loop iteration can allocate 256 bytes on the stack. If iterations is 10,000, the method could consume about 2.5 MB of stack, which might exceed the default stack size. The runtime is not required to reclaim the buffer until the method returns, and the JIT may or may not reuse the same stack slot. Do not rely on that reuse.

If you need to process many chunks, allocate the buffer once outside the loop and reuse it:

csharp
public static void ProcessInLoop(int iterations) { Span<byte> buffer = stackalloc byte[256]; for (int i = 0; i < iterations; i++) { // reuse buffer } }

This guarantees that only one buffer is allocated on the stack, regardless of the number of iterations. It is a safer and more predictable pattern for long-running loops.

Final Thoughts on Production Usage

In production code, use stackalloc deliberately. It is not a magic performance switch. It is a tool that eliminates heap allocations in specific, measured scenarios. Before adopting it, profile your application to confirm that buffer allocation is a bottleneck. After adopting it, test under realistic concurrency levels because multiple threads each consume their own stack space. A thread with a deep call stack and several stackalloc buffers combined can approach the stack limit even with moderate buffer sizes.

Keep buffer sizes small, prefer Span<T> over raw pointers, and remember that a stackalloc-created Span<T> cannot be stored in a field or used across await in an async method. With those constraints understood, stackalloc combined with Span<T> is a reliable way to write zero-allocation, high-performance code paths in C#.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.