c++ - std::pair 赋值运算符的性能问题是什么?

标签 c++ stl compiler-optimization

我看过演讲 Danila Kutenin — C++ STL best and worst performance features (包括同一个演讲的另一个版本),我已经阅读了 blog ,但我仍然不明白是什么阻止了 std::pair 赋值运算符的优化。
godbolt link of the comparison with custom pair ,代码内联在这里:

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());
}

最佳答案

这不是 C++ 的问题,而是您使用的 STL 实现的问题。
如果您编写以下检查

    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");
您会注意到只有第二行无法编译。并非所有 STL 实现都是这种情况,而只是您编译的一种,可能还有其他一些。
std::is_trivially_copyable_v<T>那么为真 std::copy的 vector T可能是优化到 memcpy 的实现级别在整个范围内,而不是为每个元素调用 copy。

关于c++ - std::pair 赋值运算符的性能问题是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64978278/

相关文章:

c++ - 如何在 Qt 中为 qmake 指定一个库文件依赖?

C++ 抽象类作为 std::map 键

c++ - 修改排序数组还是每次都对数组排序?

c - 定时 Release模式(优化)功能

c++ - 为什么编译器可以比普通函数更好地优化 lambda?

c++ - 我是否需要删除我创建的 boost 线程?

c++ - 错误 C2678 : binary '==' : no operator found which takes a left-hand operand of type

c# - volatile 是否会阻止引入的读取或写入?

c++ - 使用 mongocxx-driver 时包含头文件问题

c++ - std::vector<char> 中元素的字节对齐方式是什么?