为什么在循环外提升字符串会导致性能降低?

时间:2019-03-16 12:53:45

标签: c++

在尝试重构循环时,在检查!eof()(反模式)的地方,我发现更新的代码要慢得多。在此处查看基准测试:http://quick-bench.com/hY0cwQzDf7F3cFc-2IlA0JUDf9I

原始代码:

std::string message("hi there i am a message whoo hoo\nhi there i am a message whoo hoo\nhi there i am a message whoo hoo\nhi there i am a message whoo hoo\n");
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 hoo\nhi there i am a message whoo hoo\nhi there i am a message whoo hoo\nhi there i am a message whoo hoo\n");
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移到循环外并更改循环条件。据快速测试台介绍,使用带有-O3的Clang 7.0时,较新的版本慢15倍。这似乎是违反直觉的,但是我的理论是,由于std::getline调用erase,因此清除填充的字符串比仅创建一个新对象要昂贵得多。这个理论是正确的还是我错过了什么?

1 个答案:

答案 0 :(得分:3)

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

相关问题