capypad
0 day streak
csharp / expert
Snippet

Memory Efficiency with Span<T> and Stackalloc

Span<T> provides a type-safe and memory-safe representation of a contiguous region of arbitrary memory. By combining it with stackalloc, you can perform high-performance buffer operations entirely on the stack, bypassing the Garbage Collector and reducing memory pressure.

snippet.csharp
csharp
1
2
3
4
5
public void ProcessData(ReadOnlySpan<byte> data) {
Span<byte> buffer = stackalloc byte[128];
data.Slice(0, 64).CopyTo(buffer);
// Perform operations without heap allocation
}
Breakdown
1
Span<byte> buffer = stackalloc byte[128];
Allocates memory on the stack instead of the managed heap.
2
data.Slice(0, 64)
Creates a view over a sub-section of memory without copying data.