Improve performance reading basic strings processing

Merged
PR
4mo ago
+230-26

This PR improves performance by changing a process based on Span<T> to a process using SIMD operations with SearchValues.IndexOfAny.
I have also added test in CsTomlReader.ReadDoubleQuoteSingleLineStringSlow.

Benchmark

MethodLengthEscapedMeanErrorStdDevMedianRatioRatioSDBranchInstructions/OpBranchMispredictions/OpCode SizeAllocatedAlloc Ratio
PerByteIfChain16False24.634 ns2.5788 ns3.7800 ns25.854 ns1.020.21840272 B-NA
StopSearchValuesBulkCopy16False7.579 ns0.5605 ns0.8216 ns7.669 ns0.310.062101,495 B-NA
StopSearchValuesNoCopy16False7.496 ns2.1189 ns3.1058 ns9.712 ns0.310.1490669 B-NA
StopSearchValuesNoCopyAt16False7.888 ns2.3079 ns3.3099 ns8.884 ns0.330.1480654 B-NA
PerByteIfChain16True26.275 ns2.1176 ns3.1695 ns25.480 ns1.010.17780271 B-NA
StopSearchValuesBulkCopy16True27.771 ns1.2466 ns1.8658 ns27.722 ns1.070.147601,564 B-NA
StopSearchValuesNoCopy16True31.147 ns1.8695 ns2.7402 ns31.070 ns1.200.177602,109 B-NA
StopSearchValuesNoCopyAt16True29.880 ns1.2435 ns1.7833 ns29.973 ns1.150.157502,094 B-NA
PerByteIfChain256False416.734 ns31.6929 ns47.4364 ns419.079 ns1.010.161,2901272 B-NA
StopSearchValuesBulkCopy256False19.606 ns0.7630 ns1.1420 ns19.473 ns0.050.014401,627 B-NA
StopSearchValuesNoCopy256False12.769 ns0.7697 ns1.1521 ns12.388 ns0.030.00250672 B-NA
StopSearchValuesNoCopyAt256False13.115 ns0.8262 ns1.2366 ns13.086 ns0.030.00240659 B-NA
PerByteIfChain256True466.165 ns39.6227 ns59.3054 ns467.914 ns1.020.181,2853271 B-NA
StopSearchValuesBulkCopy256True35.249 ns3.1163 ns4.6643 ns34.577 ns0.080.019401,663 B-NA
StopSearchValuesNoCopy256True40.396 ns1.3345 ns1.9561 ns40.210 ns0.090.019602,183 B-NA
StopSearchValuesNoCopyAt256True42.210 ns4.5985 ns6.7405 ns38.633 ns0.090.029502,170 B-NA
Benchmark source
public class BasicStringScan
{
    private const byte DoubleQuote = 0x22;
    private const byte BackSlash = 0x5C;

    // control chars + '"' + '\' (34 values)
    private static readonly SearchValues<byte> StopBytes = CreateStopBytes();

    // control chars only (32 values) — post-validation for the 2-value IndexOfAny candidate
    private static readonly SearchValues<byte> ControlBytes = CreateControlBytes();

    private static SearchValues<byte> CreateStopBytes()
    {
        Span<byte> stops = stackalloc byte[34];
        var n = 0;
        for (var b = 0x00; b <= 0x08; b++) { stops[n++] = (byte)b; }
        for (var b = 0x0A; b <= 0x1F; b++) { stops[n++] = (byte)b; }
        stops[n++] = 0x7F;
        stops[n++] = DoubleQuote;
        stops[n++] = BackSlash;
        return SearchValues.Create(stops[..n]);
    }

    private static SearchValues<byte> CreateControlBytes()
    {
        Span<byte> ctrl = stackalloc byte[32];
        var n = 0;
        for (var b = 0x00; b <= 0x08; b++) { ctrl[n++] = (byte)b; }
        for (var b = 0x0A; b <= 0x1F; b++) { ctrl[n++] = (byte)b; }
        ctrl[n++] = 0x7F;
        return SearchValues.Create(ctrl[..n]);
    }

    private byte[] buffer = [];
    private readonly LabWriter writer = new(1024);

    [Params(16, 256)]
    public int Length { get; set; }

    [Params(false, true)]
    public bool Escaped { get; set; }

    [GlobalSetup]
    public void Setup()
    {
        // realistic ASCII content, closing quote, then trailing TOML
        ReadOnlySpan<byte> chars = "The quick brown fox jumps over the lazy dog 0123456789. "u8;
        ReadOnlySpan<byte> tail = "\r\nnext = 1"u8;
        buffer = new byte[Length + 1 + tail.Length];
        for (var i = 0; i < Length; i++)
        {
            buffer[i] = chars[i % chars.Length];
        }
        if (Escaped)
        {
            // two backslash escape pairs inside the content
            buffer[Length / 3] = BackSlash;
            buffer[Length / 3 + 1] = (byte)'n';
            buffer[Length * 2 / 3] = BackSlash;
            buffer[Length * 2 / 3 + 1] = (byte)'n';
        }
        buffer[Length] = DoubleQuote;
        tail.CopyTo(buffer.AsSpan(Length + 1));
    }

    // --- current implementation (CsTomlReader.ReadDoubleQuoteSingleLineString) ---

    // replica of TomlCodes.IsEscape: U+0000-U+0008, U+000A-U+001F, U+007F
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private static bool IsEscape(byte rawByte)
    {
        ReadOnlySpan<bool> escapeTable =
        [
            true, true, true, true, true, true, true, true, true, false, true, true, true, true, true, true,                 // 0x00 - 0x0f
            true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,                  // 0x10 - 0x1f
            false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,  // 0x20 - 0x2f
            false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,  // 0x30 - 0x3f
            false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,  // 0x40 - 0x4f
            false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,  // 0x50 - 0x5f
            false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,  // 0x60 - 0x6f
            false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true,   // 0x70 - 0x7f
            false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,  // 0x80 - 0x8f
            false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,  // 0x90 - 0x9f
            false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,  // 0xa0 - 0xaf
            false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,  // 0xb0 - 0xbf
            false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,  // 0xc0 - 0xcf
            false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,  // 0xd0 - 0xdf
            false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,  // 0xe0 - 0xef
            false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false,  // 0xf0 - 0xff
        ];
        return Unsafe.Add(ref MemoryMarshal.GetReference(escapeTable), rawByte);
    }

    // Escape handling is simplified for all candidates alike: on '\', append the byte
    // after it and consume 2 bytes (stands in for ParseEscapeSequence, identical cost
    // across candidates so the comparison stays focused on the scan itself).

    [MethodImpl(MethodImplOptions.NoInlining)]
    [Benchmark(Baseline = true)]
    public int PerByteIfChain()
    {
        var writer = this.writer;
        writer.Reset();
        var span = buffer.AsSpan();
        for (var index = 0; index < span.Length; index++)
        {
            var ch = span[index];
            if (IsEscape(ch))
            {
                ThrowInvalid(ch);
            }
            else if (ch == DoubleQuote)
            {
                return writer.WrittenCount;
            }
            else if (ch == BackSlash)
            {
                writer.Write(span[index + 1]);
                index++;
                continue;
            }
            writer.Write(ch);
        }
        ThrowUnclosed();
        return -1;
    }

    // --- candidates ---

    [MethodImpl(MethodImplOptions.NoInlining)]
    [Benchmark]
    public int StopSearchValuesBulkCopy()
    {
        var writer = this.writer;
        writer.Reset();
        var span = buffer.AsSpan();
        while (true)
        {
            var idx = span.IndexOfAny(StopBytes);
            if (idx < 0)
            {
                ThrowUnclosed();
            }
            var ch = span[idx];
            if (ch == DoubleQuote)
            {
                writer.Write(span[..idx]);
                return writer.WrittenCount;
            }
            if (ch != BackSlash)
            {
                ThrowInvalid(ch);
            }
            writer.Write(span[..idx]);
            writer.Write(span[idx + 1]);
            span = span[(idx + 2)..];
        }
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    [Benchmark]
    public int QuoteBackslashThenValidate()
    {
        var writer = this.writer;
        writer.Reset();
        var span = buffer.AsSpan();
        while (true)
        {
            var idx = span.IndexOfAny(DoubleQuote, BackSlash);
            if (idx < 0)
            {
                ThrowUnclosed();
            }
            var content = span[..idx];
            if (content.ContainsAny(ControlBytes))
            {
                ThrowInvalid(0);
            }
            writer.Write(content);
            if (span[idx] == DoubleQuote)
            {
                return writer.WrittenCount;
            }
            writer.Write(span[idx + 1]);
            span = span[(idx + 2)..];
        }
    }

    // Fast path for the dominant case (no backslash before the closing quote):
    // the content is one clean slice, so skip the buffer writer entirely.
    // In production this means calling T.Parse(unreadSpan[..idx]) directly.
    [MethodImpl(MethodImplOptions.NoInlining)]
    [Benchmark]
    public int StopSearchValuesNoCopy()
    {
        var span = buffer.AsSpan();
        var idx = span.IndexOfAny(StopBytes);
        if (idx < 0)
        {
            ThrowUnclosed();
        }
        var ch = span[idx];
        if (ch == DoubleQuote)
        {
            return idx; // content length; production: T.Parse(span[..idx]), no writer rented
        }
        if (ch != BackSlash)
        {
            ThrowInvalid(ch);
        }
        return NoCopySlowPath(span, idx);
    }

    // Same as StopSearchValuesNoCopy but reads the stop byte via Unsafe.Add — the bounds
    // check after IndexOfAny (asm: cmp/jae -> CORINFO_HELP_RNGCHKFAIL) is provably redundant.
    // Matches the production shape, which uses span.At(idx).
    [MethodImpl(MethodImplOptions.NoInlining)]
    [Benchmark]
    public int StopSearchValuesNoCopyAt()
    {
        var span = buffer.AsSpan();
        var idx = span.IndexOfAny(StopBytes);
        if (idx < 0)
        {
            ThrowUnclosed();
        }
        var ch = Unsafe.Add(ref MemoryMarshal.GetReference(span), idx);
        if (ch == DoubleQuote)
        {
            return idx; // content length; production: T.Parse(span[..idx]), no writer rented
        }
        if (ch != BackSlash)
        {
            ThrowInvalid(ch);
        }
        return NoCopySlowPath(span, idx);
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    private int NoCopySlowPath(ReadOnlySpan<byte> span, int idx)
    {
        // from the first escape onwards, same as StopSearchValuesBulkCopy
        var writer = this.writer;
        writer.Reset();
        while (true)
        {
            writer.Write(span[..idx]);
            writer.Write(span[idx + 1]);
            span = span[(idx + 2)..];
            idx = span.IndexOfAny(StopBytes);
            if (idx < 0)
            {
                ThrowUnclosed();
            }
            var ch = span[idx];
            if (ch == DoubleQuote)
            {
                writer.Write(span[..idx]);
                return writer.WrittenCount;
            }
            if (ch != BackSlash)
            {
                ThrowInvalid(ch);
            }
        }
    }

    // replicates ArrayPoolBufferWriter<byte> write shapes (capacity check + Unsafe.Add store);
    // capacity is pre-sized so the grow path never runs, mirroring the rented-1024 steady state.
    private sealed class LabWriter(int capacity)
    {
        private readonly byte[] buffer = new byte[capacity];
        private int index;

        public int WrittenCount => index;

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Reset() => index = 0;

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Write(byte value)
        {
            if ((uint)index >= (uint)buffer.Length)
            {
                ThrowFull();
            }
            Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(buffer), index++) = value;
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Write(ReadOnlySpan<byte> value)
        {
            if ((uint)value.Length > (uint)(buffer.Length - index))
            {
                ThrowFull();
            }
            value.CopyTo(buffer.AsSpan(index, value.Length));
            index += value.Length;
        }

        [DoesNotReturn]
        [MethodImpl(MethodImplOptions.NoInlining)]
        private static void ThrowFull()
            => throw new InvalidOperationException("LabWriter capacity exceeded.");
    }

    [DoesNotReturn]
    [MethodImpl(MethodImplOptions.NoInlining)]
    private static void ThrowInvalid(byte ch)
        => throw new InvalidOperationException($"Invalid byte in basic string: 0x{ch:X2}");

    [DoesNotReturn]
    [MethodImpl(MethodImplOptions.NoInlining)]
    private static void ThrowUnclosed()
        => throw new InvalidOperationException("Basic string is not closed.");
}