C++ ++i 或 i++ 在 for 循环中 ??
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4261708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
++i or i++ in for loops ??
提问by Ismail Marmoush
Possible Duplicate:
Is there a performance difference between i++ and ++i in C++?
Is there a reason some programmers write ++i
in a normal for loop instead of writing i++
?
有些程序员是否有理由++i
在正常的 for 循环中编写而不是编写i++
?
回答by Drew Hall
++i
is slightly more efficient due to its semantics:
++i
由于其语义,效率稍高:
++i; // Fetch i, increment it, and return it
i++; // Fetch i, copy it, increment i, return copy
For int-like indices, the efficiency gain is minimal (if any). For iterators and other heavier-weight objects, avoiding that copy can be a real win (particularly if the loop body doesn't contain much work).
对于类似 int 的索引,效率增益是最小的(如果有的话)。对于迭代器和其他重量更重的对象,避免复制可能是一个真正的胜利(特别是如果循环体不包含太多工作)。
As an example, consider the following loop using a theoretical BigInteger class providing arbitrary precision integers (and thus some sort of vector-like internals):
例如,考虑以下循环,使用理论上的 BigInteger 类提供任意精度的整数(以及某种类似向量的内部结构):
std::vector<BigInteger> vec;
for (BigInteger i = 0; i < 99999999L; i++) {
vec.push_back(i);
}
That i++ operation includes copy construction (i.e. operator new, digit-by-digit copy) and destruction (operator delete) for a loop that won't do anything more than essentially make one more copy of the index object. Essentially you've doubled the work to be done (and increased memory fragmentation most likely) by simply using the postfix increment where prefix would have been sufficient.
i++ 操作包括复制构造(即操作符新,逐位复制)和销毁(操作符删除)循环,除了本质上再制作一个索引对象的副本外,它不会做任何事情。本质上,通过简单地使用前缀足够的后缀增量,您已经将要完成的工作加倍(并且很可能增加了内存碎片)。
回答by Oliver Charlesworth
For integers, there is no difference between pre- and post-increment.
对于整数,前后增量没有区别。
If i
is an object of a non-trivial class, then ++i
is generally preferred, because the object is modified and then evaluated, whereas i++
modifies after evaluation, so requires a copy to be made.
如果i
是非平凡类的对象,则++i
通常首选,因为该对象被修改然后评估,而i++
在评估之后修改,因此需要进行复制。
回答by Richard
++i
is a pre-increment; i++
is post-increment.
The downside of post-increment is that it generates an extra value; it returns a copy of the old valuewhile modifying i
. Thus, you should avoid it when possible.
++i
是一个预增量;i++
是后增量。
后增量的缺点是它会产生一个额外的值;它在修改时返回旧值的副本i
。因此,您应该尽可能避免它。
回答by bgporter
With integers, it's preference.
对于整数,这是首选。
If the loop variable is a class/object, it can make a difference (only profiling can tell you if it's a significant difference), because the post-increment version requires that you create a copy of that object that gets discarded.
如果循环变量是一个类/对象,它可能会有所作为(只有分析可以告诉您它是否有显着差异),因为后增量版本要求您创建该对象的副本,该副本将被丢弃。
If creating that copy is an expensive operation, you're paying that expense once for every time you go through the loop, for no reason at all.
如果创建该副本是一项昂贵的操作,那么每次遍历循环时,您都将无缘无故地支付一次该费用。
If you get into the habit of always using ++i
in for loops, you don't need to stop and think about whether what you're doing in this particular situation makes sense. You just always are.
如果您养成了始终使用++i
in for 循环的习惯,则无需停下来思考在这种特定情况下您所做的事情是否有意义。你只是一直都是。
回答by wilhelmtell
There is a reason for this: performance. i++ generates a copy, and that's a waste if you immediately discard it. Granted, the compiler can optimize away this copy if i
is a primitive, but it can't if it isn't. See thisquestion.
这是有原因的:性能。i++ 生成一个副本,如果您立即丢弃它,那将是一种浪费。当然,如果i
是原始副本,编译器可以优化掉这个副本,但如果不是,则不能。看到这个问题。
回答by rtpg
No compiler worth its weight in salt will run differently between
没有任何编译器值得在盐中运行
for(int i=0; i<10; i++)
and
和
for(int i=0;i<10;++i)
++i and i++ have the same cost. The only thing that differs is that the return value of ++i is i+1 whereas the return value of i++ is i.
++i 和 i++ 具有相同的成本。唯一不同的是++i的返回值是i+1,而i++的返回值是i。
So for those prefering ++i, there's probably no valid justification, just personal preference.
所以对于那些喜欢 ++i 的人来说,可能没有有效的理由,只是个人喜好。
EDIT: This is wrong for classes, as said in about every other post. i++ will generate a copy if i is a class.
编辑:这对于课程来说是错误的,正如其他所有帖子中所述。如果 i 是一个类, i++ 将生成一个副本。
回答by fredoverflow
As others have already noted, pre-increment is usually faster than post-increment for user-defined types. To understand why this is so, look at the typical code pattern to implement both operators:
正如其他人已经指出的那样,对于用户定义的类型,预增量通常比后增量快。要理解为什么会这样,请查看实现这两个运算符的典型代码模式:
Foo& operator++()
{
some_member.increase();
return *this;
}
Foo operator++(int dummy_parameter_indicating_postfix)
{
Foo copy(*this);
++(*this);
return copy;
}
As you can see, the prefix version simply modifies the object and returns it by reference.
如您所见,前缀版本只是修改对象并通过引用返回它。
The postfix version, on the other hand, must make a copy before the actual increment is performed, and then that copy is copied back to the caller by value. It is obvious from the source code that the postfix version must do more work, because it includes a call to the prefix version: ++(*this);
另一方面,后缀版本必须在执行实际增量之前制作一个副本,然后将该副本按值复制回调用者。从源代码可以明显看出,后缀版本必须做更多的工作,因为它包括对前缀版本的调用:++(*this);
For built-in types, it does not make any difference as long as you discard the value, i.e. as long as you do not embed ++i
or i++
in a larger expression such as a = ++i
or b = i++
.
对于内置类型,它没有任何区别,只要你放弃价值,即只要你不嵌入++i
或i++
在一个更大的表达式,如a = ++i
或b = i++
。
回答by Yevhen
when you use postfix it instantiates on more object in memory. Some people say that it is better to use suffix operator in for loop
当您使用 postfix 时,它会在内存中的更多对象上实例化。有人说for循环中最好用后缀运算符
回答by John Dibling
Personal preference.
个人喜好。
Usually. Sometimes it matters but, not to seem like a jerk here, but if you have to ask, it probably doesn't.
通常。有时这很重要,但不要在这里看起来像个混蛋,但如果你不得不问,它可能不会。