⚡ Span = Memory Performance
Memory allocations slow down apps. Span
📝 Span Basics
// Span from array
int[] numbers = {1, 2, 3, 4, 5};
Span span = numbers.AsSpan();
// Slice
Span slice = span.Slice(1, 3); // {2, 3, 4}
// Modify via span
slice[0] = 10; // numbers becomes {1, 10, 3, 4, 5}
// ReadOnlySpan
ReadOnlySpan readOnly = numbers;
// Span from string (ReadOnlySpan)
ReadOnlySpan text = "Hello World".AsSpan();
ReadOnlySpan word = text.Slice(6, 5); // "World"
// Stackalloc
Span stackSpan = stackalloc int[10];
for (int i = 0; i < stackSpan.Length; i++)
{
stackSpan[i] = i;
}
🎯 Span Performance
// Fast parsing (no allocations) public static bool TryParseInt(ReadOnlySpantext, out int result) { result = 0; if (text.IsEmpty) return false; int sign = 1; int index = 0; if (text[0] == '-') { sign = -1; index = 1; } for (; index < text.Length; index++) { if (!char.IsDigit(text[index])) { return false; } result = result * 10 + (text[index] - '0'); } result *= sign; return true; }
✅ Span Benefits
- ✓ Zero allocation (stack-only)
- ✓ High performance
- ✓ Safe (bounds checking)
- ✓ Works with arrays, strings, stack
- ✓ Reduces GC pressure
"Span
enables high-performance memory operations. Zero allocation, safe access. Essential for performance-critical code."
