多次调用索引运算符的性能

use*_*356 1 c++

如果我们有以下代码:

my_struct {
   string word;
   int num;
}

vector<my_struct> vec1;

//initialize vec1 to 1000 my_struct's

for (int i = 0; i < 1000; i++) {

   // in the loop body, is it faster to use vec1[i].word directly, or
   //store it in a variable, like so (string temp = vec1[i].word)
   //and use the variable to refer temp to instead refer to the word?
}
Run Code Online (Sandbox Code Playgroud)

**编辑:上面假设在循环的每次迭代中必须多次访问该单词的特定索引处的单词

Gui*_*ris 7

使用:string temp = vec1[i].word你制作副本,所以速度会慢一些.

使用引用:string& temp = vec1[i].word相反,以防止副本的性能影响(如果它可以使更多的代码更容易阅读,我会这样做).

根据您实际执行的操作,编译器可能会以完全相同的方式优化这些版本.我会专注于在最佳代码之前编写可读代码(但仍尝试不做不必要的复制).

编辑(奖金)

正如评论中所指出的,如果你不打算修改字符串,那么编写它会更好const string& temp = vec1[i].word.它将为编译器和未来的读者提供关于您可以使用引用做什么的提示.