csharp / intermediate
Snippet
Processing Sub-Arrays Without Allocation Using Span
Span<T> provides a type-safe and memory-safe view into a contiguous region of memory. Unlike Array.Copy or Substring, slicing a Span does not create a new object on the heap, significantly improving performance in data-intensive applications.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
int[] numbers = { 10, 20, 30, 40, 50, 60 };ReadOnlySpan<int> slice = numbers.AsSpan(2, 3); // Covers 30, 40, 50int sum = 0;foreach (int n in slice){sum += n;}// No new array is created in memory
Breakdown
1
numbers.AsSpan(2, 3)
Creates a window into the existing array starting at index 2 with a length of 3.
2
foreach (int n in slice)
Iterates directly over the memory segment without allocating a sub-array.