Skip to content

Checkpoint: A Fast Record Parser

The Course
•
35 min study

Here's a realistic hot path: parsing many short records from a block of text. A clear version with Split allocates an array and several strings per line. This checkpoint rewrites one with spans, and it uses measurements to decide whether that was worth doing.

Warm up: enumerating lines

EnumerateLines walks through lines of text without any allocation. Its foreach gives you a ReadOnlySpan<char> for each line. It's the ideal start for a parser.

Lines without allocation C#
ReadOnlySpan<char> text = "one\ntwo\r\nthree";

int count = 0;
int total = 0;
foreach (ReadOnlySpan<char> line in text.EnumerateLines())
{
    count++;
    total += line.Length;
}
Console.WriteLine(count);
Console.WriteLine(total);
Check your prediction
Text
3
11

Clear first

Start with the code that's obviously correct, and test it. You then have something to compare with, and something that can be used to check the fast version's answers. This approach, comparing two implementations on many inputs, finds the edge cases that you wouldn't think of.

The baseline, and what it costs C#
string text = string.Join("\n", Enumerable.Range(0, 200).Select(i => $"sensor{i % 5},{i}"));

long before = GC.GetAllocatedBytesForCurrentThread();
long sum = 0;
foreach (string line in text.Split('\n'))
{
    string[] parts = line.Split(',');
    sum += int.Parse(parts[1]);
}
long bytes = GC.GetAllocatedBytesForCurrentThread() - before;

Console.WriteLine(sum);
Console.WriteLine(bytes > 10_000);
Check your prediction
Text
19900
True

Build it yourself

Exercise

Sensor summary

Each line is name,value, with name being any text and value a whole number. Write these two methods, which must give identical results:

  • SlowSummary(string text) uses Split and a Dictionary<string, long>.
  • FastSummary(string text) uses EnumerateLines and spans, allocating only for each new name.

Both return a sorted List<(string Name, long Total, int Count)>, with invalid lines skipped and counted. An empty line is skipped and not counted, so a trailing newline is harmless. Any other line without exactly one comma is invalid, as is a value that doesn't parse. To look up a dictionary by span without allocating a string, use GetAlternateLookup<ReadOnlySpan<char>>(), which needs the dictionary to be created with StringComparer.Ordinal.

Run both on the data in the workspace, compare the results, and print the totals. Then print whether the fast version allocated less than a quarter of what the slow one did, and test both with an empty string and with "a,1\n\nb,2\n", which has a blank line and a trailing newline.

When it works, it prints:

Text
True
sensor0: 14700 from 98
sensor1: 14600 from 98
sensor2: 14800 from 98
Invalid: 6
True
True
True
Your workspace C#
string data = string.Join("\n", Enumerable.Range(0, 300).Select(i => i % 50 == 0 ? "bad line" : $"sensor{i % 3},{i}"));
Console.WriteLine(data.Length);
Hint 1: the idea

The dictionary's values should be a small mutable struct or tuple. Look up with the span. Only when a name is new does it have to become a string.

Hint 2: a first step

Write SlowSummary and print its results first. For the fast version, begin with IndexOf(',') on each line, and don't forget the rule that there must be exactly one comma, which LastIndexOf helps with.

Show one solution
C#
string data = string.Join("\n", Enumerable.Range(0, 300).Select(i => i % 50 == 0 ? "bad line" : $"sensor{i % 3},{i}"));

Slow(data);
Fast(data);

long before = GC.GetAllocatedBytesForCurrentThread();
Summary slow = Slow(data);
long slowBytes = GC.GetAllocatedBytesForCurrentThread() - before;

before = GC.GetAllocatedBytesForCurrentThread();
Summary fast = Fast(data);
long fastBytes = GC.GetAllocatedBytesForCurrentThread() - before;

Console.WriteLine(Same(slow, fast));
foreach (var row in fast.Rows)
{
    Console.WriteLine($"{row.Name}: {row.Total} from {row.Count}");
}
Console.WriteLine($"Invalid: {fast.Invalid}");
Console.WriteLine(fastBytes * 4 < slowBytes);
Console.WriteLine(Slow("").Rows.Count == 0 && Fast("").Rows.Count == 0);
Console.WriteLine(Same(Slow("a,1\n\nb,2\n"), Fast("a,1\n\nb,2\n")));

static bool Same(Summary first, Summary second) => first.Rows.SequenceEqual(second.Rows) && first.Invalid == second.Invalid;

static Summary Slow(string text)
{
    var totals = new Dictionary<string, (long Total, int Count)>();
    int invalid = 0;
    foreach (string line in text.Split('\n'))
    {
        if (line.Length == 0)
        {
            continue;
        }
        string[] parts = line.Split(',');
        if (parts.Length != 2 || !int.TryParse(parts[1], out int value))
        {
            invalid++;
            continue;
        }
        (long total, int count) = totals.GetValueOrDefault(parts[0]);
        totals[parts[0]] = (total + value, count + 1);
    }
    return Finish(totals, invalid);
}

static Summary Fast(string text)
{
    var totals = new Dictionary<string, (long Total, int Count)>(StringComparer.Ordinal);
    var lookup = totals.GetAlternateLookup<ReadOnlySpan<char>>();
    int invalid = 0;
    foreach (ReadOnlySpan<char> line in text.AsSpan().EnumerateLines())
    {
        if (line.IsEmpty)
        {
            continue;
        }
        int comma = line.IndexOf(',');
        if (comma < 0 || comma != line.LastIndexOf(',') || !int.TryParse(line[(comma + 1)..], out int value))
        {
            invalid++;
            continue;
        }
        ReadOnlySpan<char> name = line[..comma];
        lookup.TryGetValue(name, out (long Total, int Count) current);
        lookup[name] = (current.Total + value, current.Count + 1);
    }
    return Finish(totals, invalid);
}

static Summary Finish(Dictionary<string, (long Total, int Count)> totals, int invalid)
{
    var rows = totals.Select(pair => (pair.Key, pair.Value.Total, pair.Value.Count)).OrderBy(row => row.Key).ToList();
    return new Summary(rows, invalid);
}

record Summary(List<(string Name, long Total, int Count)> Rows, int Invalid);
Text
True
sensor0: 14700 from 98
sensor1: 14600 from 98
sensor2: 14800 from 98
Invalid: 6
True
True
True

The two methods share one rule for blank lines: an empty line is skipped, not counted as invalid. Both Split('\n') and EnumerateLines produce an empty piece for the blank line and another after the trailing newline, so the rule has to be written into both loops; if only one skips them, the invalid counts differ by two. The last check, with a blank line and a trailing newline, is the comparison that catches that. The fast version allocates only when lookup[name] = … meets a new name, because the alternate lookup compares the span against the stored keys without making a string.

Compare the two versions. How much harder is the fast one to read? In a program that parses a file once a day, the slow version is the right choice. In one that parses a million records a minute, it isn't. The measurement can't decide that for you, but it can tell you the price.

Was this article helpful?

Your response is saved on this device.