csharp / intermediate
Snippet
High-Performance Memory Management with Span
Span<T> represents a contiguous region of memory. It allows for high-performance operations like slicing arrays without creating expensive copies. It is especially useful in performance-critical applications where memory allocation needs to be minimized.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
public void UpdateValues(int[] data){// Create a window (slice) into the array without copying itSpan<int> slice = data.AsSpan(1, 3);for (int i = 0; i < slice.Length; i++){slice[i] *= 10; // Directly modifies the original 'data' array}}
Breakdown
1
Span<int> slice = data.AsSpan(1, 3);
Creates a view of 3 elements starting at index 1 of the original array.
2
slice[i] *= 10;
Modifies the memory in-place; changes are reflected in the original 'data' array.