0

Is there any performance penalties has 1st sample vs. 2nd one and why?

// 1. variable is declared inside the loop body
while(isSomethingTrue == true) {
  std::string str;
  findStr(str); // str initialization
  processStr(str); // processStr does not change its argument
}

// 2. variable is declared outside the loop body
std::string str;
while(isSomethingTrue == true) {
  findStr(str);
  processStr(str);
}
4

2 回答 2

2

在循环内创建变量是一种很好的做法,以确保它们的范围仅限于该循环。此外,重要的是声明变量尽可能接近它们将被使用。

这是另一篇文章,其中包含更多信息:

在循环内声明变量,好的做法还是坏的做法?

于 2014-11-11T13:31:51.307 回答
1

一般来说,如果不是普通的旧数据,每次循环迭代都会产生运行对象的构造函数/解构函数的开销。如果是字符串:分配和解除分配 str 的内部缓冲区。如果 findStr 和 processStr 都是高性能的,这只会影响性能。

于 2014-11-11T13:27:22.123 回答