为什么在循环外举起弦会导致性能较慢
Why does hoisting a string outside a loop result in slower performance?
试图重构循环,在检查!eof()
(反模式)的情况下,我发现较新的代码较慢。请参阅此处的基准:http://quick-bench.com/hy0cwqzdf7f3cfc-2ila0judf9i
原始代码:
std::string message("hi there i am a message whoo hoonhi there i am a message whoo hoonhi there i am a message whoo hoonhi there i am a message whoo hoon");
std::vector<std::string> log_lines;
std::istringstream is(message);
while (!is.eof()) {
std::string line;
std::getline(is, line);
log_lines.emplace_back(std::move(line));
}
新代码:
std::string message("hi there i am a message whoo hoonhi there i am a message whoo hoonhi there i am a message whoo hoonhi there i am a message whoo hoon");
std::vector<std::string> log_lines;
std::istringstream is(message);
std::string line;
while (std::getline(is, line)) {
log_lines.emplace_back(line);
}
您可以看到的主要区别是将std::string line
移动到循环外并更改循环条件。根据快速台式,使用clang 7.0和-O3,较新的版本速度慢了15倍。这似乎是违反直觉的,但是我的理论是,由于std::getline
调用erase
,因此清除填充字符串比简单创建一个新对象要贵。这个理论是正确的还是我错过了什么?
在第一个程序中,您将行移入向量。在第二个中,您复制它。复制字符串可能比移动要慢得多。
相关文章:
- 与多个 for 循环与单个 for 循环 wrt 相关的性能从多映射获取数据
- 基于范围的 for 循环range_declaration中各种说明符之间的性能差异
- C++中循环的性能差异
- C++循环性能的倍数
- 在原始循环上使用boost::irange的性能损失
- OpenMP 嵌套循环处理性能
- 虚拟函数调用的性能作为 for 循环中的上限
- 在 C++ 中使用 OpenMP 并行化两个 for 循环不会提供更好的性能
- C++和Java的字符串循环性能比较
- C++:if 内部循环的性能影响
- 为什么在循环外举起弦会导致性能较慢
- openMp的多个独立for循环的性能问题
- C 的性能11现代风格的循环与老式循环
- 用于C++和性能关键型应用程序中的循环
- 奇怪的OpenCL调用C++上的副作用来提高循环性能
- 为什么asm中的这种差异对性能很重要(在未优化的ptr++与++ptr循环中)
- 具有相同索引的循环的性能
- 提高循环缓冲区或堆排序性能
- 如何在测量性能时减少循环的开销
- 性能:循环声明与循环重新初始化