Improve performance of barekey reading

Merged
PR
4mo ago
+20-17

This PR improves performance by changing a process based on Span<byte> tha checks byte by byte to a process using SIMD operations with SearchValues<byte>.

Benchmark

MethodKeyLengthMeanErrorStdDevRatioRatioSDBranchInstructions/OpBranchMispredictions/OpCode Size
SwitchLoop89.952 ns5.540 ns0.3037 ns1.000.04460NA
SwitchLoopStaticTable89.275 ns4.665 ns0.2557 ns0.930.03460NA
ClassifyTableLoop86.356 ns10.334 ns0.5664 ns0.640.05200110 B
SearchValuesIndexOf85.574 ns2.332 ns0.1278 ns0.560.02100605 B
DelimiterSearchThenValidate88.291 ns11.669 ns0.6396 ns0.830.06100829 B
SwitchLoop3245.163 ns60.105 ns3.2946 ns1.000.091661NA
SwitchLoopStaticTable3244.581 ns40.934 ns2.2438 ns0.990.081670NA
ClassifyTableLoop3220.422 ns34.516 ns1.8919 ns0.450.05680110 B
SearchValuesIndexOf325.942 ns11.385 ns0.6240 ns0.130.01130601 B
DelimiterSearchThenValidate328.199 ns3.215 ns0.1762 ns0.180.01140875 B
Benchmark source
public class UnquotedKeyScan
{
    private const byte Tab = 0x09;
    private const byte Space = 0x20;
    private const byte Dot = 0x2E;
    private const byte Equal = 0x3D;

    private static readonly SearchValues<byte> BareKeyChars =
        SearchValues.Create("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"u8);

    private static readonly SearchValues<byte> KeyDelimiters =
        SearchValues.Create([Tab, Space, Dot, Equal]);

    // 0 = invalid, 1 = bare key char, 2 = delimiter
    private static readonly byte[] ClassTable = CreateClassTable();

    private static byte[] CreateClassTable()
    {
        var table = new byte[256];
        foreach (var b in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"u8)
        {
            table[b] = 1;
        }
        table[Tab] = 2;
        table[Space] = 2;
        table[Dot] = 2;
        table[Equal] = 2;
        return table;
    }

    private byte[] buffer = [];

    [Params(8, 32)]
    public int KeyLength { get; set; }

    [GlobalSetup]
    public void Setup()
    {
        // realistic bare key content followed by " = 1234"
        ReadOnlySpan<byte> chars = "abcdefghijklmnopqrstuvwxyz_0123456789-ABCDEFGHIJKLMNOPQRSTUVWXYZ"u8;
        ReadOnlySpan<byte> tail = " = 1234"u8;
        buffer = new byte[KeyLength + tail.Length];
        for (var i = 0; i < KeyLength; i++)
        {
            buffer[i] = chars[i % chars.Length];
        }
        tail.CopyTo(buffer.AsSpan(KeyLength));
    }

    // --- current implementation (CsTomlReader.ReadUnquotedString + TomlCodes.IsBareKey) ---

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private static bool IsBareKey(byte rawByte)
    {
        ReadOnlySpan<bool> barekeyTable =
        [
            false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // 0x00 - 0x0f
            false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // 0x10 - 0x1f
            false, false, false, false, false, false, false, false, false, false, false, false, false, true, false, false,  // 0x20 - 0x2f
            true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false,           // 0x30 - 0x3f
            false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,                // 0x40 - 0x4f
            true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, true,             // 0x50 - 0x5f
            false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,                // 0x60 - 0x6f
            true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false,            // 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(barekeyTable), rawByte);
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    [Benchmark(Baseline = true)]
    public int SwitchLoop()
    {
        var span = buffer.AsSpan();
        for (var index = 0; index < span.Length; index++)
        {
            var ch = span[index];
            switch (ch)
            {
                case Tab:
                case Space:
                case Dot:
                case Equal:
                    return index;
                default:
                    if (!IsBareKey(ch))
                    {
                        ThrowInvalid(ch);
                    }
                    break;
            }
        }
        return span.Length;
    }

    private static readonly bool[] BareKeyTableArray = CreateBareKeyTableArray();

    private static bool[] CreateBareKeyTableArray()
    {
        var table = new bool[256];
        foreach (var b in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"u8)
        {
            table[b] = true;
        }
        return table;
    }

    // Same shape as SwitchLoop but the lookup is a static readonly bool[] instead of the
    // inlined RVA ReadOnlySpan<bool> local — probe for the DisassemblyDiagnoser NA issue.
    [MethodImpl(MethodImplOptions.NoInlining)]
    [Benchmark]
    public int SwitchLoopStaticTable()
    {
        var table = BareKeyTableArray;
        var span = buffer.AsSpan();
        for (var index = 0; index < span.Length; index++)
        {
            var ch = span[index];
            switch (ch)
            {
                case Tab:
                case Space:
                case Dot:
                case Equal:
                    return index;
                default:
                    if (!table[ch])
                    {
                        ThrowInvalid(ch);
                    }
                    break;
            }
        }
        return span.Length;
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    [Benchmark]
    public int ClassifyTableLoop()
    {
        var table = ClassTable;
        var span = buffer.AsSpan();
        for (var i = 0; i < span.Length; i++)
        {
            var cls = table[span[i]];
            if (cls != 1)
            {
                if (cls == 2)
                {
                    return i;
                }
                ThrowInvalid(span[i]);
            }
        }
        return span.Length;
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    [Benchmark]
    public int SearchValuesIndexOf()
    {
        var span = buffer.AsSpan();
        var index = span.IndexOfAnyExcept(BareKeyChars);
        if (index < 0)
        {
            return span.Length;
        }
        var terminator = span[index];
        if (terminator is Tab or Space or Dot or Equal)
        {
            return index;
        }
        ThrowInvalid(terminator);
        return -1;
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    [Benchmark]
    public int DelimiterSearchThenValidate()
    {
        var span = buffer.AsSpan();
        var index = span.IndexOfAny(KeyDelimiters);
        var keySpan = index < 0 ? span : span.Slice(0, index);
        if (keySpan.ContainsAnyExcept(BareKeyChars))
        {
            ThrowInvalid(0);
        }
        return index < 0 ? span.Length : index;
    }

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