text.Substring allocates a new string, and array[1..3] makes a new array. In code that runs millions of times, those allocations add up. Span<T> is a view: a pointer and a length, over memory that already exists. Slicing one is free, and writing through it changes the original.
A view, not a copy
A Span<int> over an array shares the array's memory. Slicing makes a smaller view. Predict what happens to the array.
int[] numbers = { 1, 2, 3, 4, 5 };
Span<int> middle = numbers.AsSpan(1, 3);
Console.WriteLine(middle.Length);
middle[0] = 99;
middle.Slice(1).Fill(0);
Console.WriteLine(string.Join(",", numbers));
int[] copy = numbers[1..3];
copy[0] = -1;
Console.WriteLine(numbers[1]);Check your prediction
3
1,99,0,0,5
99numbers[1..3] on an array allocates a copy, while on a span it only slices. The same syntax can have different costs.
ReadOnlySpan and text
Strings are immutable, so AsSpan gives a ReadOnlySpan<char>. Trimming and slicing are free, and many library methods accept spans. Here int.Parse reads part of a string without creating a substring.
string line = " id=4217;name=ana ";
ReadOnlySpan<char> text = line.AsSpan().Trim();
int separator = text.IndexOf(';');
ReadOnlySpan<char> first = text[..separator];
ReadOnlySpan<char> value = first[(first.IndexOf('=') + 1)..];
Console.WriteLine(int.Parse(value) + 1);
Console.WriteLine(first.StartsWith("id="));
Console.WriteLine(text[(separator + 1)..].ToString());Check your prediction
4218
True
name=anaToString allocates a real string. Do it only at the end, for the results you actually need.
stackalloc
Small temporary buffers can live on the stack, which needs no garbage collection and vanishes when the method returns. Keep them small, since stack space is limited and running out crashes the whole program. A fixed limit, as here, is the standard guard.
Console.WriteLine(Reverse("hello"));
Console.WriteLine(Reverse(new string('x', 300)).Length);
static string Reverse(string text)
{
Span<char> buffer = text.Length <= 128 ? stackalloc char[128] : new char[text.Length];
Span<char> used = buffer[..text.Length];
text.CopyTo(used);
used.Reverse();
return new string(used);
}Check your prediction
olleh
300The ref struct rules
Span<T> is a ref struct: it can live only on the stack. That's what makes it safe, because a span can't outlive what it points to. The compiler enforces this: no span fields in a class, and no span variables that stay alive across an await. Use Memory<T> when you must hold on to a slice, since it's an ordinary struct, and .Span turns it into a span when you need it.
byte[] data = { 1, 2, 3, 4 };
Memory<byte> part = data.AsMemory(1, 2);
Console.WriteLine(await SumAsync(part));
static async Task<int> SumAsync(Memory<byte> memory)
{
await Task.Yield();
int total = 0;
foreach (byte value in memory.Span)
{
total += value;
}
return total;
}Check your prediction
5Try moving Span<byte> into the async method's parameter. It's a compile error, for exactly this reason.
Your turn
Sum a CSV line without allocating
Write bool TrySumCsv(ReadOnlySpan<char> line, out int sum), which sums comma-separated whole numbers using only span operations: no Split, no Substring and no ToString. Spaces around a number are fine. If any field isn't a number it returns false, the Try pattern from Day 1, so a failure can't be mistaken for a real sum. An empty line sums to 0.
Print the sum, or invalid, for 1,2,3, 10 , 20, 1,x,3, an empty string, 5 and -1. Then use GC.GetAllocatedBytesForCurrentThread to show that 1000 calls allocate less than 1000 bytes in total.
When it works, it prints:
6
30
invalid
0
5
-1
6000
TrueReadOnlySpan<char> line = "1,2,3";
Console.WriteLine(line.IndexOf(','));Hint 1: the idea
Loop: find the next comma, take everything before it, parse it, then move the view to just past the comma. When no comma remains, what's left is the last field.
Hint 2: a first step
int.TryParse accepts a ReadOnlySpan<char>, and a Trim on the span handles the spaces. Handle the empty line first, with IsEmpty.
Show one solution
foreach (string text in new[] { "1,2,3", " 10 , 20 ", "1,x,3", "", "5", "-1" })
{
Console.WriteLine(TrySumCsv(text, out int sum) ? sum.ToString() : "invalid");
}
long before = GC.GetAllocatedBytesForCurrentThread();
int total = 0;
for (int i = 0; i < 1000; i++)
{
TrySumCsv("1,2,3", out int sum);
total += sum;
}
long after = GC.GetAllocatedBytesForCurrentThread();
Console.WriteLine(total);
Console.WriteLine(after - before < 1000);
static bool TrySumCsv(ReadOnlySpan<char> line, out int sum)
{
sum = 0;
if (line.IsEmpty)
{
return true;
}
while (true)
{
int comma = line.IndexOf(',');
ReadOnlySpan<char> field = comma < 0 ? line : line[..comma];
if (!int.TryParse(field.Trim(), out int value))
{
sum = 0;
return false;
}
sum += value;
if (comma < 0)
{
return true;
}
line = line[(comma + 1)..];
}
}6
30
invalid
0
5
-1
6000
TrueA single Substring costs more than 20 bytes, so 1000 calls that each allocated would pass the limit of 1000 bytes many times over. The limit isn't 0, because the first use of a method and the measurement itself can allocate a little. For precise numbers, use a benchmark tool on your own computer.
Completion is saved in this browser only. It does not measure mastery.