有没有之间的性能差异i++而++i如果结果不能用?
是否有差异++i,并i++在一个for循环?它只是一个语法的东西吗?
是否有一些程序员++i在正常的for循环中写入而不是写入i++?
使用类似的东西是否有任何性能差异
for(int i = 0; i < 10; i++) { ... }
Run Code Online (Sandbox Code Playgroud)
和
for(int i = 0; i < 10; ++i) { ... }
Run Code Online (Sandbox Code Playgroud)
或者编译器是否能够以这样的方式进行优化,使它们在功能相同的情况下同样快速?
编辑:这是因为我与同事讨论过这个问题,并不是因为我觉得它在任何实际意义上都是有用的优化.它主要是学术性的.
我听说在C++中,preincrements(++ i)比postincrements(i ++)快一点.真的吗?这是什么原因?
我正在编写一个程序,其中迭代器用于循环std :: vector.有人告诉我,在for语句中执行++会导致更高效的代码.换句话说,他们说:
for ( vector<string>::iterator it=my_vector.begin(); it != my_vector.end(); ++it )
Run Code Online (Sandbox Code Playgroud)
比跑得快
for ( vector<string>::iterator it=my_vector.begin(); it != my_vector.end(); it++ )
Run Code Online (Sandbox Code Playgroud)
这是真的?如果是,效率提升背后的原因是什么?它所做的全部++/++是将迭代器移动到向量中的下一个项目,不是吗?
我的同事声称对于对象类型,preincrement比post增量更有效
例如
std::vector<std::string> vec;
... insert a whole bunch of strings into vec ...
// iterate over and do stuff with vec. Is this more efficient than the next
// loop?
std::vector<std::string>::iterator it;
for (it = vec.begin(); it != vec.end(); ++it){
}
// iterate over and do stuff with vec. Is this less efficient than the previous loop?
std::vector<std::string>::iterator it;
for (it = vec.begin(); it != vec.end(); it++){
}
Run Code Online (Sandbox Code Playgroud) 我通常认为preincrement比C++中的postincrement更有效.但是,当我最近阅读" 游戏引擎架构"(第二版)这本书时,有一节说,后增量优于for循环中的preincrement.因为,正如我引用的那样,"preincrement会在代码中引入数据依赖关系 - CPU必须等待增量操作完成才能在表达式中使用它的值." 这是真的?(这真的颠覆了我对这个问题的看法.)
以下是您感兴趣的部分的引用:
5.3.2.1增量前与增量后增量
请注意,在上面的示例中,我们使用的是C++的postincrement运算符
p++,而不是preincrement运算符++p.这是一个微妙但有时重要的优化.preincrement运算符在表达式中使用其(现在已修改的)值之前递增变量的内容.postincrement运算符在使用后递增变量的内容.这意味着写入会在代码中++p引入数据依赖关系 - CPU必须等待增量操作完成才能在表达式中使用其值.在深度流水线的CPU上,这引入了一个停顿.另一方面,p++没有数据依赖性.变量的值可以立即使用,增量操作可以在以后或与其使用并行进行.无论哪种方式,管道中都没有失速.当然,在
forloop(for(init_expr; test_expr; update_expr) { ... })的"update"表达式中,前后增量之间应该没有区别.这是因为任何好的编译器都会认识到没有使用变量的值update_expr.但是在使用该值的情况下,后增量是优越的,因为它不会在CPU的管道中引入停顿.因此,养成一直使用后增量的习惯是好的,除非你绝对需要preincrement的语义.
编辑:添加"上面的例子".
void processArray(int container[], int numElements)
{
int* pBegin = &container[0];
int* pEnd = &container[numElements];
for (int* p = pBegin; p != pEnd; p++)
{
int element = *p;
// process element...
}
}
void processList(std::list<int>& container)
{
std::list<int>::iterator pBegin = …Run Code Online (Sandbox Code Playgroud) 如何迭代这个C++向量?
vector<string> features = {"X1", "X2", "X3", "X4"};
我的兴趣在于for和while循环之间的区别.我知道使用后增量值然后递增,操作返回一个恒定的预增量.
while (true) {
//...
i++;
int j = i;
}
Run Code Online (Sandbox Code Playgroud)
在这里,将j包含循环结束时的旧i或后递增i?