为什么在循环外举起弦会导致性能较慢

Why does hoisting a string outside a loop result in slower performance?

本文关键字:性能 循环 为什么      更新时间:2023-10-16

试图重构循环,在检查!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,因此清除填充字符串比简单创建一个新对象要贵。这个理论是正确的还是我错过了什么?

在第一个程序中,您将行移入向量。在第二个中,您复制它。复制字符串可能比移动要慢得多。