NoSenseEtAl
NoSenseEtAl

Reputation: 30028

What is the performance problem with std::pair assignment operator?

I have watched the talk Danila Kutenin — C++ STL best and worst performance features (including one other version of the same talk), I have read the blog, but I still do not understand what is preventing optimization of std::pair assignment operator.

godbolt link of the comparison with custom pair, code inlined here:

struct MyPair {
    int a;
    int b;
};

// slower
void CopyPair(const std::vector<std::pair<int, int>>& a,
              std::vector<std::pair<int, int>>& b) {
    std::copy(a.begin(), a.end(), b.begin());
}

// faster
void SmartCopyPair(const std::vector<MyPair>& a,
                   std::vector<MyPair>& b) {
    std::copy(a.begin(), a.end(), b.begin());
}

Upvotes: 4

Views: 499

Answers (1)

ALX23z
ALX23z

Reputation: 4713

This is not an issue of C++ but rather of the STL implementation you use.

If you write following checks

    static_assert(std::is_trivially_copyable_v<MyPair>,"MyPair is not trivially copyable");
    static_assert(std::is_trivially_copyable_v<std::pair<int,int>>,"std pair is not trivially copyable");

You'll notice that only the second line fails to compile. This isn't the case for all STL implementations but only the one you compile on and possibly some other.

When std::is_trivially_copyable_v<T> is true then std::copy of vector of T is probably implementation level optimized to memcpy on the whole range instead of calling copy per element.

Upvotes: 3

Related Questions