作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如果我有一个std::string
:
std::string s{"hello"};
for (auto &c: s)
c = std::toupper(c);
transform
代替它:
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c) -> unsigned char
{ return std::toupper(c); });
std::vector<std::string>
:
std::vector<std::string> v {"hello", "how", "are", "you"};
for (auto & s : v)
for (auto &c: s)
c = std::toupper(c);
std::transform(std::begin(v), std::end(v), std::begin(v),
[](auto s) {
std::transform(std::begin(s), std::end(s), std::begin(s),
[](unsigned char c) -> unsigned char { return std::toupper(c); });
return s;
});
transform
版本生成的
assembly和
performs相应地差一半以上,这令我感到惊讶。
std::transform
是否不是零成本的抽象,还是我使用不正确?
最佳答案
传递并通过引用返回所有内容。否则,您将创建字符串的多个副本。注意更改:[](auto& s) -> std::string& {
std::transform(std::begin(v), std::end(v), std::begin(v),
[](auto& s) -> std::string& {
std::transform(std::begin(s), std::end(s), std::begin(s),
[](unsigned char c) -> unsigned char { return std::toupper(c); });
return s;
});
static void Transform2(benchmark::State& state) {
// Code before the loop is not measured
std::vector<std::string> v {"hello", "how", "are", "you"};
for (auto _ : state) {
std::transform(std::begin(v), std::end(v), std::begin(v),
[](auto& s) {
std::transform(std::begin(s), std::end(s), std::begin(s),
[](unsigned char c) -> unsigned char { return std::toupper(c); });
return s;
});
}
}
BENCHMARK(Transform2);
static void Transform3(benchmark::State& state) {
// Code before the loop is not measured
std::vector<std::string> v {"hello", "how", "are", "you"};
for (auto _ : state) {
std::transform(std::begin(v), std::end(v), std::begin(v),
[](auto& s) -> std::string& {
std::transform(std::begin(s), std::end(s), std::begin(s),
[](unsigned char c) -> unsigned char { return std::toupper(c); });
return s;
});
}
}
BENCHMARK(Transform3);
关于c++ - 嵌套的std::transform效率低下吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61263702/
我是一名优秀的程序员,十分优秀!