gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:42:22 55 4
gpt4 key购买 nike

我看过演讲 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/

55 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com