Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么在循环外提升字符串会导致性能降低?_C++ - Fatal编程技术网

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

C++ 为什么在循环外提升字符串会导致性能降低?,c++,C++,试图重构循环,检查!eof()(一种反模式),我发现较新的代码要慢得多。请参见此处的基准: 原代码: 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_lin

试图重构循环,检查
!eof()
(一种反模式),我发现较新的代码要慢得多。请参见此处的基准:

原代码:

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(“你好,我是message whoo-hoo\nhi,我是message whoo\nhi,我是message whoo-hoo\nhi,我是message whoo-hoo\n”);
std::矢量对数线;
std::istringstream是(消息);
而(!is.eof()){
std::字符串行;
std::getline(is,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 message(“你好,我是message whoo-hoo\nhi,我是message whoo\nhi,我是message whoo-hoo\nhi,我是message whoo-hoo\n”);
std::矢量对数线;
std::istringstream是(消息);
std::字符串行;
while(std::getline(is,line)){
记录管线。将管线放回原位(管线);
}

正如您所看到的,主要区别在于将
std::string line
移动到循环外部并更改循环条件。根据quick bench,使用带有-O3的Clang 7.0,较新版本的速度慢了15倍。这似乎与直觉相反,但我的理论是,由于
std::getline
调用
erase
,因此清除填充的字符串比简单地创建一个新对象要昂贵。这个理论是正确的还是我遗漏了什么?

在第一个程序中,你把线移到向量中。第二步,你复制它。复制字符串可能比移动字符串慢得多

我运行了这两个程序,但它们的输出并不相同(在
日志行中
)。另外,您是如何测量的?您的基准测试可能正在完全优化。例如,如果编译器确定您的函数没有副作用,并且没有使用返回值,则可能会发生这种情况,因此可以忽略返回值。比较给出不同结果的两位代码的性能没有意义。您的两个示例给出了不同的输出。
push\u back
在这里更准确,
emplace\u back
在这段代码中做同样的事情。