12345ieee
12345ieee

Reputation: 509

Optimize std::vector comparison to memcmp

Consider the following code (https://godbolt.org/z/Tjf4csba4):

#include <cstring>
#include <vector>

struct box {
    unsigned char x;
    bool operator==(const box& other) const = default;
};

template <typename T>
struct container {
    std::vector<T> v;

    bool equals_vec(const container<T>& b1, const container<T>& b2) {
        return b1.v == b2.v;
    }

    bool equals_memcmp(const container<T>& b1, const container<T>& b2) {
        return b1.v.size() == b2.v.size() &&
            std::memcmp(b1.v.data(), b2.v.data(), b1.v.size()*sizeof(T)) == 0;
    }
};

template class container<box>;

because the comparison operator is trivial, the two equal_* functions do the same thing, of course the memcmp one is much faster.

I would really like the compiler to figure it out by itself, but I imagine that it's not possible (though I'd like to learn why).
So the next best thing is to constrain T in container so that the memcmp comparison is valid for such type and use that to implement equality.

I've seen in this more general question that the problem had no conclusive solution in C++20, did the landscape change in C++23? Or is there some custom concept I can write out that makes it safe?


Here is the requested benchmark: https://quick-bench.com/q/k8m93TAYjJKcNk27gnRyNRQsJ8Q
and the execution example: https://godbolt.org/z/ad8oThYhs

Upvotes: 3

Views: 198

Answers (0)

Related Questions