In a C# HTTP log parser, how do you read each line's status code and duration with ReadOnlySpan<char> instead of string.Split?
answer
- fields as ranges, not strings
- a stackalloc'd Span<Range>
- parse overloads take spans
- culture on the decimal
- ToString only to keep
basics
~20 sView the line as a ReadOnlySpan<char>, split it into a stackalloc'd Span<Range> with MemoryExtensions.Split (.NET 8), and pass the slices straight to int.Parse and double.Parse, which accept spans. Nothing allocates per line unless you call ToString.
solid answer
~40 s`string.Split(' ')` allocates a `string[]` plus one string per field on every line. With spans you write `ReadOnlySpan<char> text = line;`, then `text.Split(fields, ' ')` into a `Span<Range> fields = stackalloc Range[6]`; that overload, added in .NET 8, writes the start and end of each field and returns how many it wrote. Each field is then `text[fields[3]]`, a slice, and `int.Parse(ReadOnlySpan<char>)` and `double.Parse(ReadOnlySpan<char>, IFormatProvider)` parse it in place; pass `CultureInfo.InvariantCulture` for a decimal point that must not depend on the server's culture. `StartsWith("/api/", StringComparison.Ordinal)` tests a path without a substring. When a field count is unknown, .NET 9's `Split(' ')` enumerator yields one `Range` at a time. Call `ToString()` only on a field you must keep.
code
csharp · 17 linesusing System.Globalization;
string line = "2026-10-26T10:15:03Z GET /api/orders 200 37.5";
Span<Range> fields = stackalloc Range[6];
ReadOnlySpan<char> text = line; // string -> ReadOnlySpan<char>
int count = text.Split(fields, ' ', StringSplitOptions.RemoveEmptyEntries);
ReadOnlySpan<char> method = text[fields[1]];
ReadOnlySpan<char> path = text[fields[2]];
int status = int.Parse(text[fields[3]]);
double ms = double.Parse(text[fields[4]], CultureInfo.InvariantCulture);
Console.WriteLine($"{count} fields");
Console.WriteLine($"{method.ToString()} {status} {ms.ToString(CultureInfo.InvariantCulture)}");
Console.WriteLine(path.StartsWith("/api/", StringComparison.Ordinal));
Console.WriteLine(int.TryParse(text[fields[2]], out _)); // False: "/api/orders"go deeper
Recall that the number parsers and string helpers have ReadOnlySpan<char> overloads, so a slice can be parsed without making a substring.
Walk through the Split into Span<Range>, slicing with a Range and parsing in place, and say where the only copy happens and why.
Cover the edge cases a production parser hits: the overflow range, empty fields, malformed numbers with TryParse, invariant culture for decimals, and ordinal prefixes.
Treat span parsing as worthwhile where line volume makes allocation matter, and keep the span work inside one method that returns plain values.
## The problem with string.Split on a hot path A typical access-log line looks like `2026-10-26T10:15:03Z GET /api/orders 200 37.5`. The classic parse is `line.Split(' ')`, then `int.Parse(parts[3])`. It is correct, but on every line it allocates: - one `string[]` to hold the parts, - one new `string` for **each** field, including the ones you never read. Measured on the .NET 10 SDK, that came to 272 bytes per line for this five-field line. At a few hundred thousand lines a second, that is a steady stream of short-lived garbage for the GC to collect. The span version below allocated nothing per line. ## Step by step with spans 1. **View the line.** `ReadOnlySpan<char> text = line;` (or `line.AsSpan()`) costs nothing: it points at the string's characters. 2. **Split into ranges.** `MemoryExtensions.Split(this ReadOnlySpan<char> source, Span<Range> destination, char separator, StringSplitOptions options = StringSplitOptions.None)` (.NET 8) writes a `Range` per field into `destination` and returns the count. `destination` can be stack memory: `Span<Range> fields = stackalloc Range[6];`. 3. **Slice the field.** `text[fields[3]]` is a `ReadOnlySpan<char>` over `200`, still inside the original string. 4. **Parse in place.** `int.Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null)` and `int.TryParse(ReadOnlySpan<char>, out int)` read the slice directly; `double.Parse` has the same span overloads. 5. **Copy only what you keep.** If the path must go into a dictionary or a record, call `ToString()` on that one slice. ## Details that bite | Situation | What happens | What to do | |---|---|---| | Line has more fields than `destination` holds | The **last** range covers the rest of the line, separators included | Size `destination` one larger than the fields you read, or check the count | | Field count is unknown | A fixed `Span<Range>` may be too small | Use .NET 9's `foreach (Range r in text.Split(' '))`, which yields ranges one at a time | | Runs of spaces | Empty fields appear | Pass `StringSplitOptions.RemoveEmptyEntries` | | Duration `37.5` | `double.Parse` without a provider uses the current culture's decimal separator | Pass `CultureInfo.InvariantCulture`, since the log format is fixed | | Malformed status | `int.Parse` throws `FormatException` | Use `int.TryParse(span, out int status)` and count or skip the line | | Prefix test | `path.StartsWith("/api/")` on a span | Pass `StringComparison.Ordinal`; a log path is not natural-language text | The overflow rule in the first row was checked on the SDK: splitting the sample line into a two-element `Span<Range>` returned 2, and the second range was `GET /api/orders 200 37.5`. ## Why this is safe The slices never outlive `line`: they are spans, and spans are `ref struct`s that the compiler keeps on the stack, so a slice cannot be stored in a field or survive past the method by accident. That is exactly why the final `ToString()` is the hand-over point. Keeping the parse as a method that takes a `string` or a `ReadOnlySpan<char>` and returns plain values (`int status`, `double ms`) keeps the span work local. ## Handling bad lines without exceptions Real logs contain truncated lines, health-check noise and the occasional garbage write. A parser that uses `int.Parse` will throw `FormatException` on the first bad status field, and exceptions per line are far more expensive than the allocations you just removed. The span-friendly shape is: 1. check the count returned by `Split`; if it is lower than the field you need, count the line as malformed and move on, 2. use `int.TryParse(text[fields[3]], out int status)` and `double.TryParse(text[fields[4]], NumberStyles.Float, CultureInfo.InvariantCulture, out double ms)`, 3. return a small result (a `bool` plus `out` values, or a struct) so the caller decides what to do with rejects. The `TryParse` overloads take the same `ReadOnlySpan<char>` slices, so the error path allocates nothing either. ## Choosing between the split forms - **`Split(Span<Range>, char)`** (.NET 8): best when the format has a known, small number of fields, as an access log does; one call, no loop. - **`Split(char)` enumerator** (.NET 9): best when the count varies, such as a query string; it streams ranges. - **`IndexOf` and `Slice` by hand**: still fine for two or three fields and works on every runtime since spans arrived. What none of them change is the parsing itself: the number parsers, `Trim`, `StartsWith`, `SequenceEqual` and `IndexOf` all have span overloads, so once the line is a span, the whole pipeline can stay allocation-free.
- Your log format sometimes gains an extra trailing field; what does the Span<Range> Split overload do if there are more fields than slots?It fills every slot but the last normally and puts the whole remainder of the line, separators included, into the last range. A six-slot destination for a line with seven fields leaves the last two fields joined. Size the destination one larger than the fields you read, so the extra text lands in a slot you ignore, or check the returned count.
- Why pass CultureInfo.InvariantCulture to double.Parse on a span when int.Parse of the status code works without it?Without a provider both parsers use the current culture. For a plain integer that rarely matters, but a decimal separator does: on a server whose culture uses a comma, `37.5` will not parse as thirty-seven and a half. A log format is fixed, not user-facing, so the invariant culture is the correct provider.
- How would you keep the request path in a Dictionary<string, int> counter without allocating a string for every line?Allocate only for new keys. On .NET 9 and later, `GetAlternateLookup<ReadOnlySpan<char>>()` on a string-keyed dictionary looks up by span, so existing paths are found without a string, and you call `ToString()` only when adding a path seen for the first time. The dictionary feature itself belongs with dictionaries and sets.
- Calls ToString on every field before parsing it.
- Believes int.Parse only accepts a string, so a span must be converted first.
- Assumes the Range Split overload drops fields that do not fit.
- Parses decimals without a culture and trusts the server's settings.
- Stores the field spans in a class to use after the line is gone.
Assumes .NET 10; MemoryExtensions.Split into a Span<Range> arrived in .NET 8 and the enumerating Split(char) in .NET 9.