SWAR, and When std::string::find Isn't What You Think It Is

I’m tired, boss - me after redoing the MSVC investigation


Hello again, esteemed reader! I hope you’ve had a pleasant, what, 2 months since my last blog entry?

Well, fear not! I’m here to make sure your appetite for knowledge is, somewhat, satisfied.

In actuality, I’ve been in a sort of writer’s block. For the past few months (summer included) I’ve been staring into the void of internship-searching, and it stared back at me. Glad to say that’s finally over including a rejection after 5 rounds of interviewing; damned stack ranking.

However, I’m here to talk about the dark times - more exactly about an accidental discovery while knee-deep in the dark times.

Context

This past summer, driven in part by ambition, in part by personal spite, I was targeting HFT internships. While I had a sudden realization by the middle of the summer, I had already gone down the rabbit hole of vibecoding some projects.

I’m talking now about these because, while preparing for an interview, I decided to actually do a deep-dive into my projects. And there I found the following piece of code:

// ...

const auto half{static_cast<std::uint64_t>(delimiter << 24 | delimiter << 16 | delimiter << 8 | delimiter)};
const std::uint64_t delimMask{half << 32 | half};
for (; start + 8 <= string.size(); start += 8)
{
    std::uint64_t stringData{};
    std::memcpy(&stringData, string.data() + start, sizeof(stringData));

    std::uint64_t cmp{stringData ^ delimMask};
    std::uint64_t mask{(cmp - 0x0101010101010101ULL) & ~cmp & 0x8080808080808080ULL};
    if (mask != 0ULL)
    {
        size_t pos{static_cast<size_t>(__builtin_ctzll(mask) / 8)};
        return start + pos;
    }
}

for (; start < string.size(); ++start)
{
    if (string[start] == delimiter)
    {
        return start;
    }
}

// ...

Yes, I know exactly what you’re gonna say next: WTF? That’s what I said, at least.

I do not remember if it was an LLM who wrote that, or if I got inspired by Stack Overflow, but I did not have a clue what the fuck I was doing. That made me do the bare minimum and educate myself on the code I would, possibly, have to explain to another human.


Editor note:

While reviewing this draft, I’ve become aware of a flaw:

const auto half{static_cast<std::uint64_t>(delimiter << 24 | delimiter << 16 | delimiter << 8 | delimiter)};

Since char can be treated as a signed char (implementation defined), left shifting it is UB (before C++20, apparently). More exactly, if the char were to be negative, sign extension could take place; therefore, the mask would be corrupted.

A correct implementation would be:

const auto byte = static_cast<std::uint8_t>(delimiter);
const std::uint64_t delimMask = byte * 0x0101010101010101ULL;
This works because 0x0101010101010101 = 1 << 56 | ... | 1
==> delimiter * 0x0101010101010101 = delimiter * (1 << 56 | ... | 1) = delimiter << 56 | ... | delimiter (pseudo code)

The article will continue to use the bugged version, to stay faithful to my code.


SWAR - SIMD Within A Register

I’m not going to assume that you are familiar with either abbreviation.

Simply put, SIMD allows a processor to execute a single instruction over multiple independent data elements simultaneously. Modern CPUs provide dedicated vector registers and instructions to facilitate this.

I am still learning about it, so perhaps it will be a later topic. Today I am more focused on his lesser-known, uglier brother:

SWAR applies a similar principle without dedicated vector instructions. Instead, we pack multiple smaller data elements into a regular integer and exploit arithmetic and bitwise operations to process them in parallel.

Let’s start by dissecting my black magic, line by line. Sounds good? Great!

const auto half {static_cast<std::uint64_t>(delimiter << 24 | delimiter << 16 | delimiter << 8 | delimiter)};

Delimiter is supposed to be a char. For our example, we will be using ‘=’ (0x3D). What the line is trying to do is to have a whole 32-bit half filled by our delimiter character.

Show the `half` calculation
half = 0x00 | 0x00 | 0x00 | 0x00 | 0x3D | 0x3D | 0x3D | 0x3D
     = 0    | 0    | 0    | 0    | =    | =    | =    | =   

With this judgement, delimMask is simply going to be full of equals!

const std::uint64_t delimMask {half << 32 | half};
Show the `delimMask` representation
delimMask   = 0x3D | 0x3D | 0x3D | 0x3D | 0x3D | 0x3D | 0x3D | 0x3D
            = =    | =    | =    | =    | =    | =    | =    | =   

I’m going to skip the loop declaration. The next two lines are just copying the current 8-byte (64-bit) window into a uint64_t. We are trying to not invoke any UB (Undefined Behavior) regarding memory alignment, and the like, so instead of doing fun and hacky pointer casts (jk, do NOT do this), we’re doing a plain memcpy:

std::uint64_t stringData {};
std::memcpy(&stringData, string.data() + start, sizeof(stringData));

We are going to use the example string 10=heyyy. I am going to wait a tiny bit to see what you think this is going to look like in memory.

3.

2.

1.

Show the string's byte representation
stringData  = y    | y    | y    | e    | h    | =    | 0    | 1
            = 0x79 | 0x79 | 0x79 | 0x65 | 0x68 | 0x3D | 0x30 | 0x31

Now, you may wonder: WHY IS IT IN REVERSE? That is a very good question, for which the short answer is Little Endianness - the quality that memory is represented starting with the least significant byte. We are basically saying to the code, in a safe way:

Hey! See this region of memory that is “10=heyyy”? Interpret it as if it were an integer!

Therefore, the integer will represent it in reverse. Makes no sense? Thank Intel. But there are some advantages, check this Stack Exchange discussion for further enlightenment.

The black magic

We have now reached the bread and butter of this blog!

std::uint64_t cmp {stringData ^ delimMask};

That little arrow (^) is the XOR operator. What it does is that it sets bits that are equal in both numbers to 0, and to 1 otherwise.

We’re going to introduce the binary representation as well now:

Show the XOR calculation
delimMask   = 0x3D      | 0x3D      | 0x3D      | 0x3D      | 0x3D      | 0x3D      | 0x3D      | 0x3D
            = 00111101  | 00111101  | 00111101  | 00111101  | 00111101  | 00111101  | 00111101  | 00111101

^

stringData  = y         | y         | y         | e         | h         | =         | 0         | 1
            = 0x79      | 0x79      | 0x79      | 0x65      | 0x68      | 0x3D      | 0x30      | 0x31
            = 01111001  | 01111001  | 01111001  | 01100101  | 01101000  | 00111101  | 00110000  | 00110001

=

cmp         = 01000100  | 01000100  | 01000100  | 01011000  | 01010101  | 00000000  | 00001101  | 00001100
            = 0x44      | 0x44      | 0x44      | 0x58      | 0x55      | 0x00      | 0x0D      | 0x0C

Easy enough? Time for la crème de la crème

std::uint64_t mask {(cmp - 0x0101010101010101ULL) & ~cmp & 0x8080808080808080ULL};
if (mask != 0ULL) {
        size_t pos {static_cast<size_t>(__builtin_ctzll(mask) / 8)};
        return start + pos;
}

Basically, this mind-numbing level of bit-hacks does some simple things in order:

  • cmp - 0x0101010101010101ULL: Subtracts 1 from every byte. A 0x00 byte (our match) underflows to 0xFF, flipping its most significant bit (MSB) from 0 to 1.
  • & ~cmp: Filters out false positives from bytes that already had their MSB set (0x81–0xFF still have an MSB of 1 after subtracting 1, so ~cmp clears them).
  • & 0x8080808080808080ULL: Masks out everything except the MSB of each byte, leaving 0x80 where our delimiter was and 0x00 everywhere else.
  • __builtin_ctzll(mask) / 8: Counts the trailing zeros to find the index of the first matching byte.


There’s no need to believe me, we’re doing the math in order.

Also, Mr. Anderson probably has a much better explanation in this legendary web page

Show the zero-byte detection calculation
cmp         = 01000100  | 01000100  | 01000100  | 01011000  | 01010101  | 00000000  | 00001101  | 00001100

-
              00000001  | 00000001  | 00000001  | 00000001  | 00000001  | 00000001  | 00000001  | 00000001

result      = 01000011  | 01000011  | 01000011  | 01010111  | 01010011  | 11111111  | 00001100  | 00001011

&

~cmp        = 10111011  | 10111011  | 10111011  | 10100111  | 10101010  | 11111111  | 11110010  | 11110011

=

            = 00000011  | 00000011  | 00000011  | 00000111  | 00000010  | 11111111  | 00000000  | 00000011
            = 0x03      | 0x03      | 0x03      | 0x07      | 0x02      | 0xFF      | 0x00      | 0x03

&

              10000000  | 10000000  | 10000000  | 10000000  | 10000000  | 10000000  | 10000000  | 10000000
              0x80      | 0x80      | 0x80      | 0x80      | 0x80      | 0x80      | 0x80      | 0x80

=

mask        = 00000000  | 00000000  | 00000000  | 00000000  | 00000000  | 10000000  | 00000000  | 00000000
            = 0x00      | 0x00      | 0x00      | 0x00      | 0x00      | 0x80      | 0x00      | 0x00

__builtin_ctzll is just computer-ese for "give me how many trailing zeros this 64-bit number has". And we divide by 8 to find the byte where our bit is set. Of course, this works because my computer (like the vast majority of them) is a little-endian system.

Voila! We have a super complicated character search.

Now, you may wonder 2 things:

  1. What’s up with the end trailing loop?
  2. Is this even more efficient than a single loop, or std::string::find?

What’s up with the end trailing loop?

Remember this sentence:

We are trying to not invoke any UB (Undefined Behavior) regarding memory alignment, and the like, so instead of doing fun and hacky pointer casts, we’re doing a plain memcpy

You might think "But isn't memcpy, like, slow?" and you’d be right in 99% of the cases! However, let’s look at the code, and at what the compiler generates:

C++ Code
    std::uint64_t stringData {};
    std::memcpy(&stringData, string.data() + start, sizeof(stringData));
    
ASM Code (x86-64 gcc (trunk) -std=c++20 -O0)
    mov     QWORD PTR [rbp-64], 0
    mov     rax, QWORD PTR [rbp-72]
    mov     rdi, rax
    call    "std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::data()"
    mov     edx, DWORD PTR [rbp-76]
    movsxd  rdx, edx
    add     rax, rdx
    mov     rax, QWORD PTR [rax]
    mov     QWORD PTR [rbp-64], rax     % very nice, a simple MOV call!
    

As you can observe, there is no call to memcpy! In fact, this is such a widely used pattern in systems programming that the compiler can automatically generate the proper code! However, this only works if the memcpy size is constant. If we were to have the following code:

C++ Code
    std::uint64_t stringData {};
    std::memcpy(&stringData, string.data() + start, min(sizeof(stringData), string.size() - start));
    

The compiler would emit the following assembly:

ASM Code (x86-64 gcc (trunk) -std=c++20 -O0)
    [...]

    lea     rcx, [rax+rdx]
    lea     rax, [rbp-80]
    mov     rdx, rbx
    mov     rsi, rcx
    mov     rdi, rax
    call    "memcpy"    % you see the memcpy call?

    

Because the memcpy optimization requires a fixed 8-byte window, we need a trailing for loop to process the remaining (at most 7) bytes.

Is this even more efficient than a single loop, or std::string::find?

There’s only one way to find out - and that’s the next chapter!

However, let’s make some predictions.

Running at -O0, I believe that the SWAR version is going to be much faster than the loop version, and much slower than std::string::find, since that should be vectorized. However, running at -O3 should vectorize the loop version, so possibly SWAR will be the slowest variant.

TLDR: std::string::find > SWAR >> loop (-O0) | std::string::find >= loop >> SWAR (-O3) (spoiler: this didn’t happen)

Benchmarking: when memchr surprised me

The benchmark has been done on the following environment:

Processor: AMD Ryzen 9 5900HX with Radeon Graphics 3.30 GHz Edition: Windows 11 Pro Version: 23H2

We’re going to use an older version of g++ - the same as on my WSL machine: g++.exe (MinGW-W64 x86_64-ucrt-posix-seh, built by Brecht Sanders) 11.4.0

The benchmark itself is going to be simple: runs on strings where the character is found at the beginning, middle, and end of the string. We’re going to be using Google Benchmark to have a better look at the data:

Click to see the benchmark code
    #include <algorithm>
    #include <cstdint>
    #include <cstring>
    #include <string>

    #include <benchmark/benchmark.h>

    #ifdef _MSC_VER
    #include <intrin.h>
    static inline int __builtin_ctzll(unsigned long long x)
    {
        unsigned long idx;
        _BitScanForward64(&idx, x);
        return static_cast<int>(idx);
    }
    #endif

    int searchCharacter1(const std::string &string, int start, char delimiter)
    {
        const auto half{static_cast<std::uint64_t>(delimiter << 24 | delimiter << 16 | delimiter << 8 | delimiter)};
        const std::uint64_t delimMask{half << 32 | half};
        for (; start + 8 <= static_cast<int>(string.size()); start += 8)
        {
            std::uint64_t stringData{};
            std::memcpy(&stringData, string.data() + start, sizeof(stringData));

            std::uint64_t cmp{stringData ^ delimMask};
            std::uint64_t mask{(cmp - 0x0101010101010101ULL) & ~cmp & 0x8080808080808080ULL};
            if (mask != 0ULL)
            {
                size_t pos{static_cast<size_t>(__builtin_ctzll(mask) / 8)};
                return start + static_cast<int>(pos);
            }
        }

        for (; start < static_cast<int>(string.size()); ++start)
        {
            if (string[start] == delimiter)
            {
                return start;
            }
        }
        return -1;
    }

    int searchCharacter2(const std::string &string, int start, char delimiter)
    {
        for (; start < static_cast<int>(string.size()); start++)
        {
            if (string[start] == delimiter)
                return start;
        }
        return -1;
    }

    int searchCharacterFind(const std::string &string, int start, char delimiter)
    {
        size_t pos = string.find(delimiter, static_cast<size_t>(start));
        return (pos == std::string::npos) ? -1 : static_cast<int>(pos);
    }

    enum class PosMode { First, Middle, End };

    static std::string make_data(size_t n, PosMode mode)
    {
        std::string data(n, 'a');
        if (mode == PosMode::First)
            data[0] = ';';
        else if (mode == PosMode::Middle)
            data[n / 2] = ';';
        else
            data[n - 1] = ';';
        return data;
    }

    template <auto Fn, PosMode Mode>
    static void BM_Search(benchmark::State &state)
    {
        const size_t n = static_cast<size_t>(state.range(0));
        const std::string data = make_data(n, Mode);

        int res = 0;
        for (auto _ : state)
        {
            res = Fn(data, 0, ';');
            benchmark::DoNotOptimize(res);
        }
        const int64_t scanned = (res >= 0) ? static_cast<int64_t>(res) + 1 : static_cast<int64_t>(n);
        state.SetBytesProcessed(static_cast<int64_t>(state.iterations()) * scanned);
    }

    #define REGISTER_CASES(Mode)                                                      \
        BENCHMARK(BM_Search<searchCharacter1, Mode>)->Arg(8)->Arg(100)->Arg(1000)->Arg(10000); \
        BENCHMARK(BM_Search<searchCharacter2, Mode>)->Arg(8)->Arg(100)->Arg(1000)->Arg(10000); \
        BENCHMARK(BM_Search<searchCharacterFind, Mode>)->Arg(8)->Arg(100)->Arg(1000)->Arg(10000);

    REGISTER_CASES(PosMode::First)
    REGISTER_CASES(PosMode::Middle)
    REGISTER_CASES(PosMode::End)

    BENCHMARK_MAIN();

    

Windows results

Running the benchmark with g++ -O0:

Show benchmark results
----------------------------------------------------------------------------------------------------------------
Benchmark                                                      Time             CPU   Iterations UserCounters...
----------------------------------------------------------------------------------------------------------------
BM_Search<searchCharacter1, PosMode::First>/8               13.2 ns         12.5 ns     10000000 bytes_per_second=76.2939Mi/s
BM_Search<searchCharacter1, PosMode::First>/100             10.4 ns         9.38 ns     10000000 bytes_per_second=101.725Mi/s
BM_Search<searchCharacter1, PosMode::First>/1000            9.38 ns         7.81 ns     10000000 bytes_per_second=122.07Mi/s
BM_Search<searchCharacter1, PosMode::First>/10000           9.12 ns         9.73 ns      3211264 bytes_per_second=98Mi/s
BM_Search<searchCharacter2, PosMode::First>/8               6.18 ns         3.12 ns     10000000 bytes_per_second=305.176Mi/s
BM_Search<searchCharacter2, PosMode::First>/100             6.48 ns         6.10 ns     17920000 bytes_per_second=156.25Mi/s
BM_Search<searchCharacter2, PosMode::First>/1000            6.92 ns         6.25 ns     10000000 bytes_per_second=152.588Mi/s
BM_Search<searchCharacter2, PosMode::First>/10000           6.14 ns         4.69 ns     10000000 bytes_per_second=203.451Mi/s
BM_Search<searchCharacterFind, PosMode::First>/8            9.47 ns         9.73 ns      3211264 bytes_per_second=98Mi/s
BM_Search<searchCharacterFind, PosMode::First>/100          9.58 ns         10.9 ns     10000000 bytes_per_second=87.1931Mi/s
BM_Search<searchCharacterFind, PosMode::First>/1000         9.63 ns         5.43 ns      5754585 bytes_per_second=175.616Mi/s
BM_Search<searchCharacterFind, PosMode::First>/10000        11.0 ns         9.73 ns      3211264 bytes_per_second=98Mi/s
BM_Search<searchCharacter1, PosMode::Middle>/8              9.09 ns         9.73 ns      3211264 bytes_per_second=490Mi/s
BM_Search<searchCharacter1, PosMode::Middle>/100            34.5 ns         31.2 ns      1000000 bytes_per_second=1.51992Gi/s
BM_Search<searchCharacter1, PosMode::Middle>/1000            292 ns          312 ns       100000 bytes_per_second=1.4931Gi/s
BM_Search<searchCharacter1, PosMode::Middle>/10000          3147 ns         2433 ns        32113 bytes_per_second=1.91447Gi/s
BM_Search<searchCharacter2, PosMode::Middle>/8              26.3 ns         17.4 ns      1792000 bytes_per_second=273.438Mi/s
BM_Search<searchCharacter2, PosMode::Middle>/100             222 ns          174 ns       179200 bytes_per_second=278.906Mi/s
BM_Search<searchCharacter2, PosMode::Middle>/1000           2160 ns         3125 ns        10000 bytes_per_second=152.893Mi/s
BM_Search<searchCharacter2, PosMode::Middle>/10000         21557 ns        26158 ns         1792 bytes_per_second=182.328Mi/s
BM_Search<searchCharacterFind, PosMode::Middle>/8           10.8 ns         9.73 ns      3211264 bytes_per_second=490Mi/s
BM_Search<searchCharacterFind, PosMode::Middle>/100         23.4 ns         20.3 ns     10000000 bytes_per_second=2.33834Gi/s
BM_Search<searchCharacterFind, PosMode::Middle>/1000         169 ns          174 ns       179200 bytes_per_second=2.67563Gi/s
BM_Search<searchCharacterFind, PosMode::Middle>/10000       1280 ns         1946 ns        32113 bytes_per_second=2.39308Gi/s
BM_Search<searchCharacter1, PosMode::End>/8                 9.36 ns         9.38 ns     10000000 bytes_per_second=813.802Mi/s
BM_Search<searchCharacter1, PosMode::End>/100               75.9 ns         62.5 ns      1000000 bytes_per_second=1.49012Gi/s
BM_Search<searchCharacter1, PosMode::End>/1000               633 ns          610 ns       179200 bytes_per_second=1.52588Gi/s
BM_Search<searchCharacter1, PosMode::End>/10000             5836 ns         4688 ns        10000 bytes_per_second=1.98682Gi/s
BM_Search<searchCharacter2, PosMode::End>/8                 35.4 ns         31.2 ns      1000000 bytes_per_second=244.141Mi/s
BM_Search<searchCharacter2, PosMode::End>/100                432 ns          436 ns       179200 bytes_per_second=218.75Mi/s
BM_Search<searchCharacter2, PosMode::End>/1000              4189 ns         4688 ns        10000 bytes_per_second=203.451Mi/s
BM_Search<searchCharacter2, PosMode::End>/10000            40734 ns        31250 ns         1000 bytes_per_second=305.176Mi/s
BM_Search<searchCharacterFind, PosMode::End>/8              12.0 ns         9.38 ns     10000000 bytes_per_second=813.802Mi/s
BM_Search<searchCharacterFind, PosMode::End>/100            46.5 ns         62.5 ns      1000000 bytes_per_second=1.49012Gi/s
BM_Search<searchCharacterFind, PosMode::End>/1000            295 ns          218 ns      1792000 bytes_per_second=4.27246Gi/s
BM_Search<searchCharacterFind, PosMode::End>/10000          2736 ns         3125 ns        10000 bytes_per_second=2.98023Gi/s

MinGW GCC -O0 (First) MinGW GCC -O0 (Middle) MinGW GCC -O0 (End)

Running with g++ -O3:

Show benchmark results
----------------------------------------------------------------------------------------------------------------
Benchmark                                                      Time             CPU   Iterations UserCounters...
----------------------------------------------------------------------------------------------------------------
BM_Search<searchCharacter1, PosMode::First>/8               1.07 ns        0.938 ns    100000000 bytes_per_second=1017.25Mi/s
BM_Search<searchCharacter1, PosMode::First>/100             1.03 ns        0.872 ns    179200000 bytes_per_second=1.06812Gi/s
BM_Search<searchCharacter1, PosMode::First>/1000            1.06 ns        0.973 ns     32112640 bytes_per_second=980Mi/s
BM_Search<searchCharacter1, PosMode::First>/10000           1.06 ns        0.973 ns     32112640 bytes_per_second=980Mi/s
BM_Search<searchCharacter2, PosMode::First>/8              0.758 ns        0.781 ns    100000000 bytes_per_second=1.19209Gi/s
BM_Search<searchCharacter2, PosMode::First>/100            0.835 ns        0.785 ns    179200000 bytes_per_second=1.18679Gi/s
BM_Search<searchCharacter2, PosMode::First>/1000            1.54 ns         3.12 ns     10000000 bytes_per_second=305.176Mi/s
BM_Search<searchCharacter2, PosMode::First>/10000          0.863 ns        0.815 ns     57545851 bytes_per_second=1.14333Gi/s
BM_Search<searchCharacterFind, PosMode::First>/8            2.00 ns        0.973 ns     32112640 bytes_per_second=980Mi/s
BM_Search<searchCharacterFind, PosMode::First>/100          2.02 ns         3.49 ns     17920000 bytes_per_second=273.438Mi/s
BM_Search<searchCharacterFind, PosMode::First>/1000         1.99 ns         1.46 ns     32112640 bytes_per_second=653.333Mi/s
BM_Search<searchCharacterFind, PosMode::First>/10000        2.02 ns         2.62 ns     17920000 bytes_per_second=364.583Mi/s
BM_Search<searchCharacter1, PosMode::Middle>/8              1.05 ns         1.09 ns    100000000 bytes_per_second=4.25747Gi/s
BM_Search<searchCharacter1, PosMode::Middle>/100            4.43 ns         4.69 ns     10000000 bytes_per_second=10.1328Gi/s
BM_Search<searchCharacter1, PosMode::Middle>/1000           32.9 ns         31.2 ns      1000000 bytes_per_second=14.931Gi/s
BM_Search<searchCharacter1, PosMode::Middle>/10000           397 ns          312 ns       100000 bytes_per_second=14.9041Gi/s
BM_Search<searchCharacter2, PosMode::Middle>/8              2.54 ns         2.62 ns     17920000 bytes_per_second=1.78019Gi/s
BM_Search<searchCharacter2, PosMode::Middle>/100            27.2 ns         31.2 ns      1000000 bytes_per_second=1.51992Gi/s
BM_Search<searchCharacter2, PosMode::Middle>/1000            263 ns          312 ns       100000 bytes_per_second=1.4931Gi/s
BM_Search<searchCharacter2, PosMode::Middle>/10000          2522 ns         3125 ns        10000 bytes_per_second=1.49041Gi/s
BM_Search<searchCharacterFind, PosMode::Middle>/8           3.15 ns         3.12 ns     10000000 bytes_per_second=1.49012Gi/s
BM_Search<searchCharacterFind, PosMode::Middle>/100         15.6 ns         17.4 ns      1792000 bytes_per_second=2.72369Gi/s
BM_Search<searchCharacterFind, PosMode::Middle>/1000         163 ns          312 ns       100000 bytes_per_second=1.4931Gi/s
BM_Search<searchCharacterFind, PosMode::Middle>/10000       1332 ns          973 ns        32113 bytes_per_second=4.78617Gi/s
BM_Search<searchCharacter1, PosMode::End>/8                 1.00 ns        0.938 ns    100000000 bytes_per_second=7.94729Gi/s
BM_Search<searchCharacter1, PosMode::End>/100               8.58 ns         6.25 ns     10000000 bytes_per_second=14.9012Gi/s
BM_Search<searchCharacter1, PosMode::End>/1000              69.5 ns         46.9 ns      1000000 bytes_per_second=19.8682Gi/s
BM_Search<searchCharacter1, PosMode::End>/10000              630 ns          625 ns       100000 bytes_per_second=14.9012Gi/s
BM_Search<searchCharacter2, PosMode::End>/8                 2.77 ns         1.95 ns     32112640 bytes_per_second=3.82812Gi/s
BM_Search<searchCharacter2, PosMode::End>/100               46.0 ns         46.9 ns      1000000 bytes_per_second=1.98682Gi/s
BM_Search<searchCharacter2, PosMode::End>/1000               393 ns          349 ns       179200 bytes_per_second=2.67029Gi/s
BM_Search<searchCharacter2, PosMode::End>/10000             3801 ns         2616 ns        17920 bytes_per_second=3.56038Gi/s
BM_Search<searchCharacterFind, PosMode::End>/8              4.21 ns         2.62 ns     17920000 bytes_per_second=2.84831Gi/s
BM_Search<searchCharacterFind, PosMode::End>/100            35.9 ns         17.4 ns      1792000 bytes_per_second=5.34058Gi/s
BM_Search<searchCharacterFind, PosMode::End>/1000            271 ns          174 ns       179200 bytes_per_second=5.34058Gi/s
BM_Search<searchCharacterFind, PosMode::End>/10000          2758 ns         2656 ns       100000 bytes_per_second=3.50616Gi/s

MinGW GCC -O3 (First) MinGW GCC -O3 (Middle) MinGW GCC -O3 (End)

Hmm, very interesting. While running with -O0 we can see that std::string::find >> SWAR, when running with -O3 we get the exact opposite effect. I was expecting std::string::find and loop to use SIMD.

The following makes it all make sense: std::string::find is using pre-compiled library code, while the SWAR variant is compiled with -O3. This means that the optimization touches only our part of the code, not the linked library. However, this means 1 of 2 things:

  1. SWAR is faster than SIMD vectorization (very highly unlikely)
  2. the library code is not vectorized on my machine

Using GDB to breakpoint memchr (aka what std::string::find calls), we get the following disassembly:

ASM Code
    Dump of assembler code for function ucrtbase!memchr:
    => 0x00007ff8132110d0 <+0>:     test   %r8,%r8
    0x00007ff8132110d3 <+3>:     je     0x7ff8132110e2 <ucrtbase!memchr+18>
    0x00007ff8132110d5 <+5>:     cmp    %dl,(%rcx)
    0x00007ff8132110d7 <+7>:     je     0x7ff8132110e2 <ucrtbase!memchr+18>
    0x00007ff8132110d9 <+9>:     inc    %rcx
    0x00007ff8132110dc <+12>:    sub    $0x1,%r8
    0x00007ff8132110e0 <+16>:    jne    0x7ff8132110d5 <ucrtbase!memchr+5>
    0x00007ff8132110e2 <+18>:    neg    %r8
    0x00007ff8132110e5 <+21>:    sbb    %rax,%rax
    0x00007ff8132110e8 <+24>:    and    %rcx,%rax
    0x00007ff8132110eb <+27>:    ret
    0x00007ff8132110ec <+28>:    int3
    0x00007ff8132110ed <+29>:    int3
    0x00007ff8132110ee <+30>:    int3
    0x00007ff8132110ef <+31>:    int3
    0x00007ff8132110f0 <+32>:    int3
    0x00007ff8132110f1 <+33>:    int3
    0x00007ff8132110f2 <+34>:    int3
    0x00007ff8132110f3 <+35>:    int3
    0x00007ff8132110f4 <+36>:    int3
    0x00007ff8132110f5 <+37>:    int3
    0x00007ff8132110f6 <+38>:    data16 nopw 0x0(%rax,%rax,1)
    

There’s no sign of vectorization! So I am guessing that on my machine memchr is not 100% optimized.

Even with this part of the explanation, there’s still the Scalar loop enigma.

Compiling with the -fopt-info-vec-all flag yields the following:

bench.cpp:39:18: note: *** Analysis failed with vector mode V2DI bench.cpp:39:18: note: *** Skipping vector mode V16QI, which would repeat the analysis for V2DI

This confirms that our loop couldn’t be vectorized. As to why? Our loop has multiple possible exits. GCC optimizations are conservative, and trying to vectorize such a loop could risk going out-of-bounds. That being the case, however, I was hoping the compiler would do some magic.

We should still check this benchmark on a Linux machine. For this experiment, I’m going to use WSL2.

Debugging further on WSL2

We are running on the following environment:

WSL version: 3.0.5.0 Kernel version: 6.18.58.1-1 g++ version: g++ (Ubuntu 11.4.0-1ubuntu1~22.04.3) 11.4.0

Running the same tests on WSL2:

$ g++ bench.cpp -O0 -o ./bench

Show benchmark results
----------------------------------------------------------------------------------------------------------------
Benchmark                                                      Time             CPU   Iterations UserCounters...
----------------------------------------------------------------------------------------------------------------
BM_Search<searchCharacter1, PosMode::First>/8               11.1 ns         12.1 ns      2754090 bytes_per_second=78.6307Mi/s
BM_Search<searchCharacter1, PosMode::First>/100             12.3 ns         13.4 ns      2449289 bytes_per_second=71.1923Mi/s
BM_Search<searchCharacter1, PosMode::First>/1000            13.5 ns         14.7 ns      1394905 bytes_per_second=64.79Mi/s
BM_Search<searchCharacter1, PosMode::First>/10000           10.2 ns         11.1 ns      2407195 bytes_per_second=85.6344Mi/s
BM_Search<searchCharacter2, PosMode::First>/8               7.28 ns         7.95 ns      3806545 bytes_per_second=120Mi/s
BM_Search<searchCharacter2, PosMode::First>/100             6.89 ns         7.51 ns      3095993 bytes_per_second=126.907Mi/s
BM_Search<searchCharacter2, PosMode::First>/1000            6.29 ns         6.85 ns      4078548 bytes_per_second=139.211Mi/s
BM_Search<searchCharacter2, PosMode::First>/10000           6.39 ns         6.98 ns      3760438 bytes_per_second=136.694Mi/s
BM_Search<searchCharacterFind, PosMode::First>/8            11.1 ns         12.1 ns      2074647 bytes_per_second=78.6568Mi/s
BM_Search<searchCharacterFind, PosMode::First>/100          11.4 ns         12.5 ns      2231727 bytes_per_second=76.4146Mi/s
BM_Search<searchCharacterFind, PosMode::First>/1000         9.84 ns         10.7 ns      2592497 bytes_per_second=88.8008Mi/s
BM_Search<searchCharacterFind, PosMode::First>/10000        9.81 ns         10.7 ns      2593924 bytes_per_second=89.114Mi/s
BM_Search<searchCharacter1, PosMode::Middle>/8              10.7 ns         11.6 ns      2823361 bytes_per_second=410.132Mi/s
BM_Search<searchCharacter1, PosMode::Middle>/100            35.9 ns         39.2 ns       717528 bytes_per_second=1.2132Gi/s
BM_Search<searchCharacter1, PosMode::Middle>/1000            289 ns          316 ns        87910 bytes_per_second=1.47804Gi/s
BM_Search<searchCharacter1, PosMode::Middle>/10000          2732 ns         2981 ns         9397 bytes_per_second=1.56239Gi/s
BM_Search<searchCharacter2, PosMode::Middle>/8              21.0 ns         22.9 ns      1268169 bytes_per_second=208.284Mi/s
BM_Search<searchCharacter2, PosMode::Middle>/100             208 ns          227 ns       131094 bytes_per_second=214.207Mi/s
BM_Search<searchCharacter2, PosMode::Middle>/1000           1923 ns         2098 ns        13285 bytes_per_second=227.741Mi/s
BM_Search<searchCharacter2, PosMode::Middle>/10000         18669 ns        20368 ns         1342 bytes_per_second=234.155Mi/s
BM_Search<searchCharacterFind, PosMode::Middle>/8           9.29 ns         10.1 ns      2779997 bytes_per_second=470.228Mi/s
BM_Search<searchCharacterFind, PosMode::Middle>/100         10.7 ns         11.7 ns      2499853 bytes_per_second=4.07543Gi/s
BM_Search<searchCharacterFind, PosMode::Middle>/1000        15.0 ns         16.4 ns      1693008 bytes_per_second=28.5271Gi/s
BM_Search<searchCharacterFind, PosMode::Middle>/10000       37.0 ns         40.4 ns       646793 bytes_per_second=115.326Gi/s
BM_Search<searchCharacter1, PosMode::End>/8                 12.3 ns         13.4 ns      2819942 bytes_per_second=568.83Mi/s
BM_Search<searchCharacter1, PosMode::End>/100               84.7 ns         92.5 ns       300453 bytes_per_second=1.0073Gi/s
BM_Search<searchCharacter1, PosMode::End>/1000               590 ns          643 ns        40997 bytes_per_second=1.44728Gi/s
BM_Search<searchCharacter1, PosMode::End>/10000             5700 ns         6219 ns         4641 bytes_per_second=1.49764Gi/s
BM_Search<searchCharacter2, PosMode::End>/8                 32.0 ns         34.9 ns       801971 bytes_per_second=218.309Mi/s
BM_Search<searchCharacter2, PosMode::End>/100                379 ns          413 ns        67969 bytes_per_second=230.79Mi/s
BM_Search<searchCharacter2, PosMode::End>/1000              3672 ns         4006 ns         6974 bytes_per_second=238.075Mi/s
BM_Search<searchCharacter2, PosMode::End>/10000            36683 ns        40000 ns          699 bytes_per_second=238.421Mi/s
BM_Search<searchCharacterFind, PosMode::End>/8              9.79 ns         10.7 ns      2725795 bytes_per_second=714.319Mi/s
BM_Search<searchCharacterFind, PosMode::End>/100            11.0 ns         12.0 ns      2267822 bytes_per_second=7.74614Gi/s
BM_Search<searchCharacterFind, PosMode::End>/1000           20.4 ns         22.3 ns      1384107 bytes_per_second=41.7492Gi/s
BM_Search<searchCharacterFind, PosMode::End>/10000          80.3 ns         87.5 ns       395151 bytes_per_second=106.487Gi/s

WSL GCC -O0 (First) WSL GCC -O0 (Middle) WSL GCC -O0 (End)

$ g++ bench.cpp -O3 -o ./bench

Show benchmark results
----------------------------------------------------------------------------------------------------------------
Benchmark                                                      Time             CPU   Iterations UserCounters...
----------------------------------------------------------------------------------------------------------------
BM_Search<searchCharacter1, PosMode::First>/8              0.937 ns         1.02 ns     27464101 bytes_per_second=932.935Mi/s
BM_Search<searchCharacter1, PosMode::First>/100             1.17 ns         1.28 ns     27891419 bytes_per_second=744.946Mi/s
BM_Search<searchCharacter1, PosMode::First>/1000            1.22 ns         1.34 ns     18971951 bytes_per_second=714.25Mi/s
BM_Search<searchCharacter1, PosMode::First>/10000           1.50 ns         1.63 ns     21031658 bytes_per_second=583.925Mi/s
BM_Search<searchCharacter2, PosMode::First>/8               1.13 ns         1.23 ns     22471311 bytes_per_second=775.012Mi/s
BM_Search<searchCharacter2, PosMode::First>/100             1.09 ns         1.18 ns     21032164 bytes_per_second=805.052Mi/s
BM_Search<searchCharacter2, PosMode::First>/1000           0.960 ns         1.05 ns     28412553 bytes_per_second=910.639Mi/s
BM_Search<searchCharacter2, PosMode::First>/10000           1.05 ns         1.15 ns     30098494 bytes_per_second=832.665Mi/s
BM_Search<searchCharacterFind, PosMode::First>/8            2.55 ns         2.79 ns      8418053 bytes_per_second=342.249Mi/s
BM_Search<searchCharacterFind, PosMode::First>/100          2.51 ns         2.74 ns     10205368 bytes_per_second=347.684Mi/s
BM_Search<searchCharacterFind, PosMode::First>/1000         2.84 ns         3.10 ns     10202981 bytes_per_second=307.819Mi/s
BM_Search<searchCharacterFind, PosMode::First>/10000        3.10 ns         3.39 ns      7655414 bytes_per_second=281.632Mi/s
BM_Search<searchCharacter1, PosMode::Middle>/8              1.11 ns         1.21 ns     22762005 bytes_per_second=3.84924Gi/s
BM_Search<searchCharacter1, PosMode::Middle>/100            5.49 ns         5.98 ns      5671342 bytes_per_second=7.93764Gi/s
BM_Search<searchCharacter1, PosMode::Middle>/1000           43.1 ns         47.1 ns       571179 bytes_per_second=9.9124Gi/s
BM_Search<searchCharacter1, PosMode::Middle>/10000           379 ns          413 ns        63198 bytes_per_second=11.2657Gi/s
BM_Search<searchCharacter2, PosMode::Middle>/8              1.75 ns         1.91 ns     11255069 bytes_per_second=2.44388Gi/s
BM_Search<searchCharacter2, PosMode::Middle>/100            17.5 ns         19.1 ns      1143041 bytes_per_second=2.49162Gi/s
BM_Search<searchCharacter2, PosMode::Middle>/1000            179 ns          196 ns       142124 bytes_per_second=2.38393Gi/s
BM_Search<searchCharacter2, PosMode::Middle>/10000          1728 ns         1886 ns        14800 bytes_per_second=2.46992Gi/s
BM_Search<searchCharacterFind, PosMode::Middle>/8           2.52 ns         2.75 ns     10223284 bytes_per_second=1.69628Gi/s
BM_Search<searchCharacterFind, PosMode::Middle>/100         3.22 ns         3.51 ns      7974997 bytes_per_second=13.5416Gi/s
BM_Search<searchCharacterFind, PosMode::Middle>/1000        5.10 ns         5.57 ns      5014387 bytes_per_second=83.7904Gi/s
BM_Search<searchCharacterFind, PosMode::Middle>/10000       23.0 ns         25.1 ns      1105739 bytes_per_second=185.886Gi/s
BM_Search<searchCharacter1, PosMode::End>/8                 1.02 ns         1.12 ns     24361513 bytes_per_second=6.67995Gi/s
BM_Search<searchCharacter1, PosMode::End>/100               7.84 ns         8.56 ns      3156142 bytes_per_second=10.8844Gi/s
BM_Search<searchCharacter1, PosMode::End>/1000              63.3 ns         69.1 ns       388030 bytes_per_second=13.4767Gi/s
BM_Search<searchCharacter1, PosMode::End>/10000              580 ns          633 ns        44411 bytes_per_second=14.7213Gi/s
BM_Search<searchCharacter2, PosMode::End>/8                 2.53 ns         2.76 ns     10229574 bytes_per_second=2.69745Gi/s
BM_Search<searchCharacter2, PosMode::End>/100               44.5 ns         48.6 ns       546913 bytes_per_second=1.91613Gi/s
BM_Search<searchCharacter2, PosMode::End>/1000               523 ns          571 ns        65305 bytes_per_second=1.63143Gi/s
BM_Search<searchCharacter2, PosMode::End>/10000             4059 ns         4429 ns         5943 bytes_per_second=2.10287Gi/s
BM_Search<searchCharacterFind, PosMode::End>/8              2.70 ns         2.94 ns      9322836 bytes_per_second=2.52994Gi/s
BM_Search<searchCharacterFind, PosMode::End>/100            3.66 ns         3.99 ns      6933654 bytes_per_second=23.3242Gi/s
BM_Search<searchCharacterFind, PosMode::End>/1000           7.84 ns         8.55 ns      3291298 bytes_per_second=108.868Gi/s
BM_Search<searchCharacterFind, PosMode::End>/10000          43.3 ns         47.3 ns       600929 bytes_per_second=197.062Gi/s

WSL GCC -O3 (First) WSL GCC -O3 (Middle) WSL GCC -O3 (End)

These results are promising. We can see that std::string::find is now up to 10x faster than our SWAR version.

Using gdb again:

ASM Code
    Dump of assembler code for function memchr_ifunc:
    => 0x00007ffff78a9310 <+0>:     endbr64
        0x00007ffff78a9314 <+4>:     mov    0x170bad(%rip),%rcx        # 0x7ffff7a19ec8
        0x00007ffff78a931b <+11>:    lea    0xb47e(%rip),%rax        # 0x7ffff78b47a0 <__memchr_sse2>
        0x00007ffff78a9322 <+18>:    mov    0xb8(%rcx),%edx
        0x00007ffff78a9328 <+24>:    mov    %edx,%esi
        0x00007ffff78a932a <+26>:    and    $0x120,%esi
        0x00007ffff78a9330 <+32>:    cmp    $0x120,%esi
        0x00007ffff78a9336 <+38>:    je     0x7ffff78a9340 <memchr_ifunc+48>
        0x00007ffff78a9338 <+40>:    ret
        0x00007ffff78a9339 <+41>:    nopl   0x0(%rax)
        0x00007ffff78a9340 <+48>:    mov    0x1a4(%rcx),%ecx
        0x00007ffff78a9346 <+54>:    test   $0x2,%ch
        0x00007ffff78a9349 <+57>:    je     0x7ffff78a9338 <memchr_ifunc+40>
        0x00007ffff78a934b <+59>:    mov    %edx,%esi
        0x00007ffff78a934d <+61>:    and    $0x800,%esi
        0x00007ffff78a9353 <+67>:    test   %edx,%edx
        0x00007ffff78a9355 <+69>:    js     0x7ffff78a9380 <memchr_ifunc+112>
        0x00007ffff78a9357 <+71>:    lea    0xfdee2(%rip),%rax        # 0x7ffff79a7240 <__memchr_avx2_rtm>
        0x00007ffff78a935e <+78>:    test   %esi,%esi
        0x00007ffff78a9360 <+80>:    jne    0x7ffff78a9338 <memchr_ifunc+40>
        0x00007ffff78a9362 <+82>:    and    $0x4,%ch
        0x00007ffff78a9365 <+85>:    lea    0xeffd4(%rip),%rdx        # 0x7ffff7999340 <__memchr_avx2>
        0x00007ffff78a936c <+92>:    lea    0xb42d(%rip),%rax        # 0x7ffff78b47a0 <__memchr_sse2>
        0x00007ffff78a9373 <+99>:    cmove  %rdx,%rax
        0x00007ffff78a9377 <+103>:   ret
        0x00007ffff78a9378 <+104>:   nopl   0x0(%rax,%rax,1)
        0x00007ffff78a9380 <+112>:   and    $0x40000000,%edx
        0x00007ffff78a9386 <+118>:   je     0x7ffff78a9357 <memchr_ifunc+71>
        0x00007ffff78a9388 <+120>:   test   %esi,%esi
        0x00007ffff78a938a <+122>:   lea    0x1051ef(%rip),%rdx        # 0x7ffff79ae580 <__memchr_evex>
        0x00007ffff78a9391 <+129>:   lea    0x10c8a8(%rip),%rax        # 0x7ffff79b5c40 <__memchr_evex_rtm>
        0x00007ffff78a9398 <+136>:   cmove  %rdx,%rax
        0x00007ffff78a939c <+140>:   ret
    End of assembler dump.
    

After running breakpoints on all possible variants, my C runtime seems to pick __memchr_avx2:

Snippet of the dump of __memchr_avx2
    Dump of assembler code for function __memchr_avx2:
    => 0x00007ffff7999340 <+0>:     endbr64
        [...]

        % The important part ---
        vpbroadcastb %xmm0, %ymm0
        vpcmpeqb     (%rdi), %ymm0, %ymm1      % uses 256-bit YMM registers!
        vpmovmskb    %ymm1, %eax
        tzcnt        %eax, %eax
        % ---

        [...]

    End of assembler dump.
    

Running the same -fopt-info-vec-all flag while compiling yields the following:

bench.cpp:43:18: note: ***** Analysis failed with vector mode V2DI bench.cpp:43:18: note: ***** Skipping vector mode V16QI, which would repeat the analysis for V2DI

Same error as above!

Why was my C runtime unvectorized?

After doing a quick investigation, I’ve found the following page:

In Visual Studio 2015, the CRT was refactored into new binaries. The Universal CRT (UCRT) contains the functions and globals exported by the standard C99 CRT library. The UCRT is now a Windows component, and ships as part of Windows 10 and later versions. The static library, DLL import library, and header files for the UCRT are now found in the Windows SDK.

The vcruntime library contains Visual C++ CRT implementation-specific code: exception handling and debugging support, runtime checks and type information, implementation details, and certain extended library functions. The vcruntime library version needs to match the version of the compiler you’re using.

This is further backed up by a separate investigation on Ruby’s issue tracker, that took place ~1 month before the time of posting.

Inspecting the tables, the SDK is found in the ucrtbase.dll file (remember, in the benchmarks we used ucrtbase!memchr!), and the MSVC runtime is found in vcruntime<version>.dll.

In this regard, the g++ compiler and MSVC Runtime differ. While libstdc++ uses memchr in its string::find implementation, it seems that MSVC has 2 different possibilities:

  1. by default, it uses its own vectorized algorithms
  2. by building with _USE_STD_VECTOR_ALGORITHMS=0, it defaults back to memchr

Running the benchmark again with cl /O2 /std:c++20 /EHsc bench.cpp (this uses the MSVC STL’s manually vectorized implementation)

Show benchmark results
----------------------------------------------------------------------------------------------------------------
Benchmark                                                      Time             CPU   Iterations UserCounters...
----------------------------------------------------------------------------------------------------------------
BM_Search<searchCharacter1, PosMode::First>/8               4.30 ns         3.12 ns     10000000 bytes_per_second=305.176Mi/s
BM_Search<searchCharacter1, PosMode::First>/100             4.71 ns         4.36 ns     17920000 bytes_per_second=218.75Mi/s
BM_Search<searchCharacter1, PosMode::First>/1000            4.27 ns         3.12 ns     10000000 bytes_per_second=305.176Mi/s
BM_Search<searchCharacter1, PosMode::First>/10000           4.56 ns         3.12 ns     10000000 bytes_per_second=305.176Mi/s
BM_Search<searchCharacter2, PosMode::First>/8               1.79 ns         1.74 ns     17920000 bytes_per_second=546.875Mi/s
BM_Search<searchCharacter2, PosMode::First>/100             1.84 ns         1.74 ns     17920000 bytes_per_second=546.875Mi/s
BM_Search<searchCharacter2, PosMode::First>/1000            1.79 ns         1.74 ns     17920000 bytes_per_second=546.875Mi/s
BM_Search<searchCharacter2, PosMode::First>/10000           1.76 ns         1.57 ns    179200000 bytes_per_second=607.639Mi/s
BM_Search<searchCharacterFind, PosMode::First>/8            3.72 ns         3.49 ns     17920000 bytes_per_second=273.438Mi/s
BM_Search<searchCharacterFind, PosMode::First>/100          3.23 ns         3.12 ns     10000000 bytes_per_second=305.176Mi/s
BM_Search<searchCharacterFind, PosMode::First>/1000         3.26 ns         3.12 ns     10000000 bytes_per_second=305.176Mi/s
BM_Search<searchCharacterFind, PosMode::First>/10000        3.23 ns         3.12 ns     10000000 bytes_per_second=305.176Mi/s
BM_Search<searchCharacter1, PosMode::Middle>/8              4.24 ns         4.69 ns     10000000 bytes_per_second=1017.25Mi/s
BM_Search<searchCharacter1, PosMode::Middle>/100            8.01 ns         9.38 ns     10000000 bytes_per_second=5.06639Gi/s
BM_Search<searchCharacter1, PosMode::Middle>/1000           53.0 ns         46.9 ns      1000000 bytes_per_second=9.95398Gi/s
BM_Search<searchCharacter1, PosMode::Middle>/10000           405 ns          312 ns       100000 bytes_per_second=14.9041Gi/s
BM_Search<searchCharacter2, PosMode::Middle>/8              3.84 ns         3.49 ns     17920000 bytes_per_second=1.33514Gi/s
BM_Search<searchCharacter2, PosMode::Middle>/100            28.1 ns         26.2 ns      1792000 bytes_per_second=1.8158Gi/s
BM_Search<searchCharacter2, PosMode::Middle>/1000            259 ns          312 ns       100000 bytes_per_second=1.4931Gi/s
BM_Search<searchCharacter2, PosMode::Middle>/10000          2535 ns         3125 ns        10000 bytes_per_second=1.49041Gi/s
BM_Search<searchCharacterFind, PosMode::Middle>/8           5.06 ns         4.69 ns     10000000 bytes_per_second=1017.25Mi/s
BM_Search<searchCharacterFind, PosMode::Middle>/100         3.98 ns         4.69 ns     10000000 bytes_per_second=10.1328Gi/s
BM_Search<searchCharacterFind, PosMode::Middle>/1000        9.66 ns         10.9 ns     10000000 bytes_per_second=42.6599Gi/s
BM_Search<searchCharacterFind, PosMode::Middle>/10000       90.3 ns         93.8 ns      1000000 bytes_per_second=49.6805Gi/s
BM_Search<searchCharacter1, PosMode::End>/8                 4.34 ns         6.25 ns     10000000 bytes_per_second=1.19209Gi/s
BM_Search<searchCharacter1, PosMode::End>/100               12.5 ns         14.6 ns      3211264 bytes_per_second=6.38021Gi/s
BM_Search<searchCharacter1, PosMode::End>/1000              93.6 ns         93.8 ns      1000000 bytes_per_second=9.93411Gi/s
BM_Search<searchCharacter1, PosMode::End>/10000              809 ns          815 ns        57546 bytes_per_second=11.4334Gi/s
BM_Search<searchCharacter2, PosMode::End>/8                 4.73 ns         3.12 ns     10000000 bytes_per_second=2.38419Gi/s
BM_Search<searchCharacter2, PosMode::End>/100               56.9 ns         31.2 ns      1000000 bytes_per_second=2.98023Gi/s
BM_Search<searchCharacter2, PosMode::End>/1000               504 ns          625 ns       100000 bytes_per_second=1.49012Gi/s
BM_Search<searchCharacter2, PosMode::End>/10000             5171 ns         4688 ns        10000 bytes_per_second=1.98682Gi/s
BM_Search<searchCharacterFind, PosMode::End>/8              5.92 ns         6.10 ns     17920000 bytes_per_second=1.2207Gi/s
BM_Search<searchCharacterFind, PosMode::End>/100            4.53 ns         3.49 ns     17920000 bytes_per_second=26.7029Gi/s
BM_Search<searchCharacterFind, PosMode::End>/1000           21.9 ns         31.2 ns      1000000 bytes_per_second=29.8023Gi/s
BM_Search<searchCharacterFind, PosMode::End>/10000           170 ns          262 ns       179200 bytes_per_second=35.6038Gi/s

MSVC /O2 (First) MSVC /O2 (Middle) MSVC /O2 (End)

Through some disassembly we notice this version is also using ymm (256-bit) registers:

0000000140006C10: C5 E5 74 09        vpcmpeqb    ymm1,ymm3,ymmword ptr [rcx]
0000000140006C45: C5 FD 74 CB        vpcmpeqb    ymm1,ymm0,ymm3

As we can see, the performance has degraded quite a bit when compared to the WSL runs - ~1.8x slower on average (and up to ~3.9x worse) However, comparing MSVC to WSL glibc is a bit like comparing apples to oranges, it is still the sole vectorized implementation we can offer a comparison with. When comparing to the Windows g++ -O3 version we see that, while MSVC is up to 16.87x faster on string::find, g++ runs faster in SWAR and Scalar - GCC manages to load the string.data() pointer only once, while MSVC reloads in the loop hot path.

Dump of the g++ version
    Dump of assembler code for function _Z16searchCharacter1RKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEic:
        
        % in x64 ABI, the args are stored in registers

        0x00000001400016d0 <+0>:     push   %r12
        0x00000001400016d2 <+2>:     push   %rbp
        0x00000001400016d3 <+3>:     push   %rdi
        0x00000001400016d4 <+4>:     push   %rsi
        0x00000001400016d5 <+5>:     push   %rbx
        0x00000001400016d6 <+6>:     mov    0x8(%rcx),%r12  % r12 will store string.size()
        0x00000001400016da <+10>:    mov    %r12d,%edi
        0x00000001400016dd <+13>:    movsbl %r8b,%eax
        0x00000001400016e1 <+17>:    mov    %edx,%r9d       % r9d contains the initial start
        0x00000001400016e4 <+20>:    mov    %r8d,%r10d
        0x00000001400016e7 <+23>:    mov    %rcx,%rsi       % the string is also in %rsi (restored later in the trailing loop)
        0x00000001400016ea <+26>:    mov    %eax,%edx
        0x00000001400016ec <+28>:    shl    $0x18,%r10d
        0x00000001400016f0 <+32>:    mov    %r8d,%ebx
        0x00000001400016f3 <+35>:    shl    $0x10,%edx
        0x00000001400016f6 <+38>:    or     %edx,%r10d
        0x00000001400016f9 <+41>:    or     %eax,%r10d
        0x00000001400016fc <+44>:    shl    $0x8,%eax
        0x00000001400016ff <+47>:    or     %eax,%r10d
        0x0000000140001702 <+50>:    movslq %r10d,%rax
        0x0000000140001705 <+53>:    shl    $0x20,%r10
        0x0000000140001709 <+57>:    or     %rax,%r10
        0x000000014000170c <+60>:    lea    0x7(%r9),%eax
        0x0000000140001710 <+64>:    cmp    %r12d,%eax
        0x0000000140001713 <+67>:    jge    0x14000177c <_Z16searchCharacter1RKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEic+172>
        0x0000000140001715 <+69>:    lea    -0x8(%r12),%eax
        0x000000014000171a <+74>:    movslq %r9d,%r8
        0x000000014000171d <+77>:    add    (%rcx),%r8      % r8 is initialized with data() + start
        0x0000000140001720 <+80>:    movabs $0xfefefefefefefeff,%rbp
        0x000000014000172a <+90>:    movabs $0x8080808080808080,%r11
        0x0000000140001734 <+100>:   sub    %r9d,%eax
        0x0000000140001737 <+103>:   and    $0xfffffff8,%eax
        0x000000014000173a <+106>:   lea    0x8(%r9,%rax,1),%ecx
        0x000000014000173f <+111>:   jmp    0x140001755 <_Z16searchCharacter1RKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEic+133>
        0x0000000140001741 <+113>:   nopl   0x0(%rax)
        0x0000000140001748 <+120>:   add    $0x8,%r9d       % increment the start variable
        0x000000014000174c <+124>:   add    $0x8,%r8        % increment the data ptr
        0x0000000140001750 <+128>:   cmp    %r9d,%ecx
        0x0000000140001753 <+131>:   je     0x140001780 <_Z16searchCharacter1RKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEic+176>
        0x0000000140001755 <+133>:   mov    (%r8),%rdx
        0x0000000140001758 <+136>:   xor    %r10,%rdx
        0x000000014000175b <+139>:   lea    (%rdx,%rbp,1),%rax
        0x000000014000175f <+143>:   not    %rdx
        0x0000000140001762 <+146>:   and    %rdx,%rax       
        0x0000000140001765 <+149>:   and    %r11,%rax
        0x0000000140001768 <+152>:   je     0x140001748 <_Z16searchCharacter1RKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEic+120>
        0x000000014000176a <+154>:   tzcnt  %rax,%rax
        0x000000014000176f <+159>:   sar    $0x3,%eax
        0x0000000140001772 <+162>:   add    %r9d,%eax
        0x0000000140001775 <+165>:   pop    %rbx
        0x0000000140001776 <+166>:   pop    %rsi
        0x0000000140001777 <+167>:   pop    %rdi
        0x0000000140001778 <+168>:   pop    %rbp
        0x0000000140001779 <+169>:   pop    %r12
        0x000000014000177b <+171>:   ret
        0x000000014000177c <+172>:   mov    %r9d,%ecx
        0x000000014000177f <+175>:   nop
        0x0000000140001780 <+176>:   cmp    %ecx,%r12d
        0x0000000140001783 <+179>:   jle    0x1400017a8 <_Z16searchCharacter1RKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEic+216>
        0x0000000140001785 <+181>:   mov    (%rsi),%r8
        0x0000000140001788 <+184>:   movslq %ecx,%rdx
        0x000000014000178b <+187>:   jmp    0x140001798 <_Z16searchCharacter1RKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEic+200>
        0x000000014000178d <+189>:   nopl   (%rax)
        0x0000000140001790 <+192>:   add    $0x1,%rdx
        0x0000000140001794 <+196>:   cmp    %edx,%edi
        0x0000000140001796 <+198>:   jle    0x1400017a8 <_Z16searchCharacter1RKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEic+216>
        0x0000000140001798 <+200>:   mov    %edx,%eax
        0x000000014000179a <+202>:   cmp    %bl,(%r8,%rdx,1)
        0x000000014000179e <+206>:   jne    0x140001790 <_Z16searchCharacter1RKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEic+192>
        0x00000001400017a0 <+208>:   jmp    0x140001775 <_Z16searchCharacter1RKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEic+165>
        0x00000001400017a2 <+210>:   nopw   0x0(%rax,%rax,1)
        0x00000001400017a8 <+216>:   mov    $0xffffffff,%eax
        0x00000001400017ad <+221>:   pop    %rbx
        0x00000001400017ae <+222>:   pop    %rsi
        0x00000001400017af <+223>:   pop    %rdi
        0x00000001400017b0 <+224>:   pop    %rbp
        0x00000001400017b1 <+225>:   pop    %r12
        0x00000001400017b3 <+227>:   ret
        0x00000001400017b4 <+228>:   data16 cs nopw 0x0(%rax,%rax,1)
        0x00000001400017bf <+239>:   nop
        End of assembler dump.
    
Dump of the MSVC version
    ?searchCharacter1@@YAHAEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@HD@Z PROC
        $LN56:
        mov    QWORD PTR [rsp+8], rbx
        mov    QWORD PTR [rsp+16], rbp
        mov    QWORD PTR [rsp+24], rsi
        mov    QWORD PTR [rsp+32], rdi
        push   r14
        push   r15

        movsxd r11, DWORD PTR [rcx+16]    ; string.size()
        movsxd r9, edx                    ; start
        movsx  rbx, r8b                   ; delimiter
        mov    edx, ebx
        shl    edx, 8
        or     edx, ebx
        shl    edx, 8
        or     edx, ebx
        shl    edx, 8
        movsxd rdx, edx
        or     rdx, rbx
        mov    rbp, rdx
        shl    rbp, 32
        or     rbp, rdx                   ; delimMask

        lea    edx, DWORD PTR [r9+8]
        cmp    edx, r11d
        jg     SHORT $LN46@searchChar

        mov    rdi, QWORD PTR [rcx+24]    ; _Myres
        mov    r8, r9
        mov    r14, -72340172838076673    ; -0x0101010101010101
        mov    r15, -9187201950435737472  ; 0x8080808080808080

        $LL4@searchChar:
        mov    r10, rcx
        cmp    rdi, 15                    ; SSO (short string optimization)
        jbe    SHORT $LN47@searchChar
        mov    r10, QWORD PTR [rcx]       ; loading again
        $LN47@searchChar:
        mov    rax, rbp
        xor    rax, QWORD PTR [r8+r10]
        lea    r10, QWORD PTR [rax+r14]
        not    rax
        and    r10, rax
        and    r10, r15
        jne    SHORT $LN35@searchChar

        add    r9d, 8
        add    edx, 8
        add    r8, 8
        cmp    edx, r11d
        jle    SHORT $LL4@searchChar

        $LN46@searchChar:
        cmp    r9d, r11d
        jge    SHORT $LN6@searchChar
        mov    r10, QWORD PTR [rcx+24]
        movsxd rax, r9d

        $LL7@searchChar:
        mov    rdx, rcx
        cmp    r10, 15
        jbe    SHORT $LN27@searchChar
        mov    rdx, QWORD PTR [rcx]
        $LN27@searchChar:
        cmp    BYTE PTR [rax+rdx], bl
        je     SHORT $LN36@searchChar
        inc    r9d
        inc    rax
        cmp    rax, r11
        jl     SHORT $LL7@searchChar

        $LN6@searchChar:
        mov    eax, -1

        $LN1@searchChar:
        mov    rbx, QWORD PTR [rsp+24]
        mov    rbp, QWORD PTR [rsp+32]
        mov    rsi, QWORD PTR [rsp+40]
        mov    rdi, QWORD PTR [rsp+48]
        pop    r15
        pop    r14
        ret    0

        $LN35@searchChar:
        bsf    rax, r10
        cdq
        and    edx, 7
        add    eax, edx
        sar    eax, 3
        add    eax, r9d
        jmp    SHORT $LN1@searchChar

        $LN36@searchChar:
        mov    eax, r9d
        jmp    SHORT $LN1@searchChar
        ?searchCharacter1@@YAHAEBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@HD@Z ENDP
    

Running the benchmark with cl /D_USE_STD_VECTOR_ALGORITHMS=0 /O2 /std:c++20 /EHsc bench.cpp

Show benchmark results
----------------------------------------------------------------------------------------------------------------
Benchmark                                                      Time             CPU   Iterations UserCounters...
----------------------------------------------------------------------------------------------------------------
BM_Search<searchCharacter1, PosMode::First>/8               4.89 ns         3.12 ns     10000000 bytes_per_second=305.176Mi/s
BM_Search<searchCharacter1, PosMode::First>/100             4.51 ns         1.74 ns     17920000 bytes_per_second=546.875Mi/s
BM_Search<searchCharacter1, PosMode::First>/1000            4.32 ns         6.25 ns     10000000 bytes_per_second=152.588Mi/s
BM_Search<searchCharacter1, PosMode::First>/10000           4.22 ns         3.49 ns     17920000 bytes_per_second=273.438Mi/s
BM_Search<searchCharacter2, PosMode::First>/8               2.01 ns         2.62 ns     17920000 bytes_per_second=364.583Mi/s
BM_Search<searchCharacter2, PosMode::First>/100             2.01 ns         1.74 ns     17920000 bytes_per_second=546.875Mi/s
BM_Search<searchCharacter2, PosMode::First>/1000            1.99 ns         1.74 ns     17920000 bytes_per_second=546.875Mi/s
BM_Search<searchCharacter2, PosMode::First>/10000           1.99 ns         3.12 ns     10000000 bytes_per_second=305.176Mi/s
BM_Search<searchCharacterFind, PosMode::First>/8            4.01 ns         3.49 ns     17920000 bytes_per_second=273.438Mi/s
BM_Search<searchCharacterFind, PosMode::First>/100          3.84 ns         4.69 ns     10000000 bytes_per_second=203.451Mi/s
BM_Search<searchCharacterFind, PosMode::First>/1000         3.88 ns         4.36 ns     17920000 bytes_per_second=218.75Mi/s
BM_Search<searchCharacterFind, PosMode::First>/10000        3.30 ns         2.66 ns    100000000 bytes_per_second=359.03Mi/s
BM_Search<searchCharacter1, PosMode::Middle>/8              4.49 ns         4.36 ns     17920000 bytes_per_second=1.06812Gi/s
BM_Search<searchCharacter1, PosMode::Middle>/100            8.15 ns         8.72 ns     17920000 bytes_per_second=5.44739Gi/s
BM_Search<searchCharacter1, PosMode::Middle>/1000           53.7 ns         31.2 ns      1000000 bytes_per_second=14.931Gi/s
BM_Search<searchCharacter1, PosMode::Middle>/10000           405 ns          344 ns      1000000 bytes_per_second=13.5492Gi/s
BM_Search<searchCharacter2, PosMode::Middle>/8              3.74 ns         5.23 ns     17920000 bytes_per_second=911.458Mi/s
BM_Search<searchCharacter2, PosMode::Middle>/100            27.3 ns         31.2 ns      1000000 bytes_per_second=1.51992Gi/s
BM_Search<searchCharacter2, PosMode::Middle>/1000            268 ns          262 ns       179200 bytes_per_second=1.78375Gi/s
BM_Search<searchCharacter2, PosMode::Middle>/10000          2672 ns         4688 ns        10000 bytes_per_second=1017.46Mi/s
BM_Search<searchCharacterFind, PosMode::Middle>/8           4.95 ns         4.69 ns     10000000 bytes_per_second=1017.25Mi/s
BM_Search<searchCharacterFind, PosMode::Middle>/100         5.76 ns         1.74 ns     17920000 bytes_per_second=27.2369Gi/s
BM_Search<searchCharacterFind, PosMode::Middle>/1000        30.0 ns         31.2 ns      1000000 bytes_per_second=14.931Gi/s
BM_Search<searchCharacterFind, PosMode::Middle>/10000        315 ns          349 ns       179200 bytes_per_second=13.3541Gi/s
BM_Search<searchCharacter1, PosMode::End>/8                 6.36 ns         4.69 ns     10000000 bytes_per_second=1.58946Gi/s
BM_Search<searchCharacter1, PosMode::End>/100               13.0 ns         15.6 ns     10000000 bytes_per_second=5.96046Gi/s
BM_Search<searchCharacter1, PosMode::End>/1000               111 ns          105 ns      1792000 bytes_per_second=8.90096Gi/s
BM_Search<searchCharacter1, PosMode::End>/10000              831 ns          781 ns       100000 bytes_per_second=11.9209Gi/s
BM_Search<searchCharacter2, PosMode::End>/8                 5.36 ns         4.69 ns     10000000 bytes_per_second=1.58946Gi/s
BM_Search<searchCharacter2, PosMode::End>/100               58.5 ns          312 ns       100000 bytes_per_second=305.176Mi/s
BM_Search<searchCharacter2, PosMode::End>/1000               699 ns          262 ns       179200 bytes_per_second=3.56038Gi/s
BM_Search<searchCharacter2, PosMode::End>/10000             5347 ns         4531 ns       100000 bytes_per_second=2.05533Gi/s
BM_Search<searchCharacterFind, PosMode::End>/8              6.16 ns         6.25 ns     10000000 bytes_per_second=1.19209Gi/s
BM_Search<searchCharacterFind, PosMode::End>/100            11.5 ns         9.73 ns      3211264 bytes_per_second=9.57031Gi/s
BM_Search<searchCharacterFind, PosMode::End>/1000           64.8 ns         31.2 ns      1000000 bytes_per_second=29.8023Gi/s
BM_Search<searchCharacterFind, PosMode::End>/10000           615 ns         1744 ns        17920 bytes_per_second=5.34058Gi/s

MSVC /O2 (_USE_STD_VECTOR_ALGORITHMS=0) (First) MSVC /O2 (_USE_STD_VECTOR_ALGORITHMS=0) (Middle) MSVC /O2 (_USE_STD_VECTOR_ALGORITHMS=0) (End)

Doing a quick disasm while running with gdb, we can notice the memchr call:

Snippet of vcruntime140!memchr
    Dump of assembler code for function memchr:
    => 0x00007ff8011b1e90 <+0>:     movzbl %dl,%edx
        0x00007ff8011b1e93 <+3>:     imul   $0x1010101,%edx,%edx    % I see you MSOFT devs!
        0x00007ff8011b1e99 <+9>:     movd   %edx,%xmm0
        0x00007ff8011b1e9d <+13>:    pshufd $0x0,%xmm0,%xmm0        % also notice the XMM registers!
        0x00007ff8011b1ea2 <+18>:    xor    %eax,%eax
        0x00007ff8011b1ea4 <+20>:    cmp    $0x20,%r8
        0x00007ff8011b1ea8 <+24>:    jb     0x7ff8011b1f09 <memchr+121>
        0x00007ff8011b1eaa <+26>:    mov    %ecx,%eax
        0x00007ff8011b1eac <+28>:    and    $0xf,%eax
        0x00007ff8011b1eaf <+31>:    je     0x7ff8011b1ed0 <memchr+64>
        0x00007ff8011b1eb1 <+33>:    sub    $0x10,%rax
        0x00007ff8011b1eb5 <+37>:    add    %rax,%r8
        0x00007ff8011b1eb8 <+40>:    sub    %rax,%rcx
        0x00007ff8011b1ebb <+43>:    nopl   0x0(%rax,%rax,1)
        0x00007ff8011b1ec0 <+48>:    cmp    (%rcx,%rax,1),%dl
        0x00007ff8011b1ec3 <+51>:    je     0x7ff8011b1f1c <memchr+140>
        0x00007ff8011b1ec5 <+53>:    inc    %rax
        0x00007ff8011b1ec8 <+56>:    jne    0x7ff8011b1ec0 <memchr+48>
        0x00007ff8011b1eca <+58>:    cmp    $0x20,%r8
        0x00007ff8011b1ece <+62>:    jb     0x7ff8011b1f09 <memchr+121>
        0x00007ff8011b1ed0 <+64>:    movdqa (%rcx),%xmm1
        0x00007ff8011b1ed4 <+68>:    pcmpeqb %xmm0,%xmm1
        0x00007ff8011b1ed8 <+72>:    pmovmskb %xmm1,%rax
        0x00007ff8011b1edd <+77>:    bsf    %rax,%rax
        0x00007ff8011b1ee1 <+81>:    jne    0x7ff8011b1f1c <memchr+140>
        0x00007ff8011b1ee3 <+83>:    movdqa 0x10(%rcx),%xmm1
        0x00007ff8011b1ee8 <+88>:    add    $0x10,%rcx
        0x00007ff8011b1eec <+92>:    pcmpeqb %xmm0,%xmm1

    

Overall, GCC generated tighter code than MSVC for our SWAR and Scalar loops (by moving string.data() out of the hot loop), while on std::string::find, WSL2’s glibc __memchr_avx2 still comfortably outperformed both MSVC’s vectorized STL and vcruntime140!memchr.

But to answer the chapter’s question: my initial benchmark was using ucrtbase!memchr, which comes by default with Windows (IN MY BUILD VERSION), and seems to not make use of vectorization. Of the Windows runtimes I checked, only vcruntime140’s memchr is vectorized.

MSVC’s string::find implementation, therefore, is vectorized, either by default (_USE_STD_VECTOR_ALGORITHMS), or by the virtue of using vcruntime!memchr. libstdc++’s string::find defaults to a memchr call, which in my Windows OS, pointed to UCRT’s implementation.


Editor’s note

After checking my dll’s build version, it would seem I am running an outdated version of Windows 11:

(Get-Item “$env:WINDIR\System32\ucrtbase.dll”).VersionInfo.FileVersion 10.0.22621.3593 (WinBuild.160101.0800)

That would check out with the Ruby Issue mentioned earlier:

On Windows 11 (10.0.26300.9711, ucrtbase.dll 10.0.26100.9711), memchr in ucrtbase.dll is no longer a byte-by-byte loop. It uses SSE2 and checks 32 bytes per iteration. Inputs shorter than 32 bytes still use a byte loop.

It seems newer build versions have fixed this problem, therefore the actuality of my finding rests only on the # of devices still running outdated versions.


Conclusions

Okay, I think we’ve played enough with objdump and gdb. You, my dear reader, are probably very tired from looking at all of this archaic “nonsense” that I’ve provided here. However, here are a few observations to keep in mind for the future:

  • exploiting the bits out of numbers can be really mind-blowing
  • using memcpy is not a death sentence on performance, since compilers are very smart - don’t be ‘smart’ with pointer tricks!
  • you have to be very thorough when investigating weird results - you probably are missing some important information!
  • knowing your hardware/runtime is probably one of the most important things a dev can do
  • I should probably update my Windows version soon


Moreover, even though the benchmark is somewhat minimal, it is still very informative about the optimizations, or lack thereof, that come prebuilt with your compiler’s C runtime - and about the ever-growing list of differences between Windows’s runtimes and Unix-based runtimes.

All in all, I can say that it’s been a fun journey to write this entry. It’s been one of my first times really understanding what my (not Godbolt’s) compilers produced - and I’ve really enjoyed it!

I hope that in my ramblings you’ve also been able to find something interesting, or even useful!

There’s probably going to be some sort of gap again before I post something new, so I wish you a very Merry Christmas close to your loved ones, a Happy New Year, and, for my Romanian readers:

LA MULTI ANI ROMANIA! (cu intarziere :()