csharp / beginner
Snippet
High-Efficiency Stack Storage
Using stackalloc manages memory on the stack instead of the heap, which is faster and reduces the work for the Garbage Collector in high-performance scenarios.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
using System;public void QuickCalculation(){// Allocates memory directly on the stack for fast accessSpan<int> coordinates = stackalloc int[2];coordinates[0] = 10;coordinates[1] = 20;}
Breakdown
1
Span<int>
A type-safe representation of a contiguous region of memory.
2
stackalloc int[2]
Allocates a small array on the execution stack.