0 day streak
csharp / expert
Snippet

Memory-Safe String Slicing via ReadOnlySpan

Using ReadOnlySpan<char> allows for high-performance string manipulation by pointing directly to existing memory. This eliminates heap allocations during slicing, which is critical for low-latency systems and high-throughput data processing.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
public void ParsePayload(string data)
{
// Avoids creating a new string object on the heap
ReadOnlySpan<char> span = data.AsSpan();
int start = data.IndexOf(':') + 1;
ReadOnlySpan<char> segment = span.Slice(start, 5);
if (segment.SequenceEqual("DEBUG"))
{
EnableVerboseLogging();
}
}
Breakdown
1
data.AsSpan()
Creates a value-type view over the string without copying data.
2
span.Slice(start, 5)
Creates a sub-view of the original memory window.