Re: why not use i++ instead of ++i in for()?
From: Mark S (mark110.DONTSPAMME_at_mindspring.com)
Date: 02/23/04
- Previous message: CheckAbdoul: "Re: why not use i++ instead of ++i in for()?"
- In reply to: r norman: "Re: why not use i++ instead of ++i in for()?"
- Next in thread: r norman: "Re: why not use i++ instead of ++i in for()?"
- Reply: r norman: "Re: why not use i++ instead of ++i in for()?"
- Reply: Bo Persson: "Re: why not use i++ instead of ++i in for()?"
- Messages sorted by: [ date ] [ thread ]
Date: Mon, 23 Feb 2004 00:22:33 GMT
"r norman" <rsn_@_comcast.net> wrote in message
news:6due309in9sbtd7oa6hhn1lkp9bp3pairv@4ax.com...
> On Sat, 21 Feb 2004 21:49:21 +0800, "snnn" <amethyst_sun@sohu.com>
> wrote:
> >yes,here,i++ and ++i has the same effect;
> >but,if the type of i is an iterator of vector(or other else),++i is more
> >fast than i++;
> >why not write all ++i instead?
> >
>
> "Usually" depends on who is writing the code. You also say that the
> pre-increment is faster than the post-increment. What gives you that
> idea? If neither the pre-incremented value nor the post-incremented
> value is used, I believe that most compilers will simply produce the
> same code.
Scott Meyer's "More Effective C++", "Item 6: Distinguish between prefix and
postfix forms of increment and decrement operators" goes into great detail
about pre and postfix operators and what the differences are.
When it comes to basic types like "int", I'm not sure if there is enough of
a difference to worry about, but as the previous poster points out, if i is
an iterator, or some other more complicated class, the pre-increment is more
efficient.
The reason for this is that with a pre-increment operator, the object is
incremented, and then it returns a reference to itself. The post-increment
operator would need to save a copy of it's old value, increment itself, and
return that old copy by value. That results in extra temporary(s) and copy
constructors being called.
So I typically always use ++i, out of habit.
Another thing I do when working with strings or other classes that give me a
choice between + and +=, when I want to concatenate a handful of strings:
s = a + b + c + d;
is not as efficient as
s = a;
s += b;
s += c;
s += d;
Again, think about the temporaries that are being used and returned.
-mark
- Previous message: CheckAbdoul: "Re: why not use i++ instead of ++i in for()?"
- In reply to: r norman: "Re: why not use i++ instead of ++i in for()?"
- Next in thread: r norman: "Re: why not use i++ instead of ++i in for()?"
- Reply: r norman: "Re: why not use i++ instead of ++i in for()?"
- Reply: Bo Persson: "Re: why not use i++ instead of ++i in for()?"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|