473,403 Members | 2,222 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

++u or u++ which is faster?

Hi all,

Recently I was asked the question about whether ++U or U++ is
faster if U is a user defined type. What's the answer?

Thank you
Jul 22 '05 #1
22 1874
The Doctor wrote:
Hi all,

Recently I was asked the question about whether ++U or U++ is
faster if U is a user defined type. What's the answer?

Thank you

http://www.parashift.com/c++-faq-lit...html#faq-13.12

--
Sumit Rajan <sumitrajan AT alexandria DOT cc>
Jul 22 '05 #2
The Doctor posted:
Hi all,

Recently I was asked the question about whether ++U or U++ is
faster if U is a user defined type. What's the answer?

Thank you

++u is faster.
Always use ++u. Never use u++ unless you need to.
-JKop

Jul 22 '05 #3
Usually operator ++ (int) is implemented like this:

T operator ++ (int)
{
T tmp = *this;
++*this;
return tmp;
}

If compiler isn't able to optimize away the initialization of the temporary
then using u++ is slower. That's why it is usually better to use
pre-increment/pre-decrement instead of post-decrement/post-increment.

VH

"The Doctor" <do****@nospam.com> wrote in message
news:Xn**********************************@61.9.191 .5...
Hi all,

Recently I was asked the question about whether ++U or U++ is
faster if U is a user defined type. What's the answer?

Thank you

Jul 22 '05 #4

"The Doctor" <do****@nospam.com> wrote in message
news:Xn**********************************@61.9.191 .5...
Hi all,

Recently I was asked the question about whether ++U or U++ is
faster if U is a user defined type. What's the answer?

Thank you


The simple answer is when using U++, the object U needs to get copied twice
whereas with ++U, it need only be copied once.

So use ++U unless you specifically require the value of the post-increment.
Jul 22 '05 #5

"JKop" <NU**@NULL.NULL> schrieb im Newsbeitrag
news:I0*******************@news.indigo.ie...
The Doctor posted:
Hi all,

Recently I was asked the question about whether ++U or U++ is
faster if U is a user defined type. What's the answer?

Thank you

++u is faster.


This general statement is not true. It depends on the datatype and the
optimization of the compiler. Both types might be the same speed, but as you
say it's generally wise to use ++u.


Always use ++u. Never use u++ unless you need to.
-JKop

Jul 22 '05 #6
JKop wrote:
++u is faster.

For built-in types their speed is the same. For user defined types it
applies what you say.

--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #7
Ioannis Vranos <iv*@guesswh.at.grad.com> wrote:
JKop wrote:
++u is faster.

For built-in types their speed is the same. For user defined types it
applies what you say.


So lets state:
++u is never slower.

Now it's perfect ;P
--
Simon Stienen <http://dangerouscat.net> <http://slashlife.de>
»What you do in this world is a matter of no consequence,
The question is, what can you make people believe that you have done.«
-- Sherlock Holmes in "A Study in Scarlet" by Sir Arthur Conan Doyle
Jul 22 '05 #8
Method Man wrote:

"The Doctor" <do****@nospam.com> wrote in message
news:Xn**********************************@61.9.191 .5...
Hi all,

Recently I was asked the question about whether ++U or U++ is
faster if U is a user defined type. What's the answer?

Thank you


The simple answer is when using U++, the object U needs to get copied
twice whereas with ++U, it need only be copied once.


What would that extra copy be needed for? I can see U++ doing at most 2
copies (but usually one - or if the function gets inlined and the return
value is not used even both - of them getting optimized away) and ++U doing
none at all. Consider the operators for an iterator into a linked list:

class mylistiterator
{
public:
//...

mylistiterator& operator++()
{
node = node->next;
return *this;
} // no copy made

mylistiterator operator++(int)
{
myiterator ret = *this; // first copy
node = node->next;
return ret; // second one, usually optimized away
}
private:
mylist::node* node;
};

So it stands 0 to 2 copies for postfix++ vs. 0 for prefix++.

Jul 22 '05 #9
> > The simple answer is when using U++, the object U needs to get copied
twice whereas with ++U, it need only be copied once.
What would that extra copy be needed for? I can see U++ doing at most 2
copies (but usually one - or if the function gets inlined and the return
value is not used even both - of them getting optimized away)


One time to store the old value, and another time for returning the old
value. Of course any optimizations are compiler-specific, dependent on
things like inlining, register variables, etc, or dependent on the
++operator code if U is a user type.

But I was speaking theoretically.
and ++U doing
none at all.
...


You're probably right here.

I guess the bottom line is U++ is never faster than ++U.
Jul 22 '05 #10
Simon Stienen posted:
Ioannis Vranos <iv*@guesswh.at.grad.com> wrote:
JKop wrote:
++u is faster.

For built-in types their speed is the same. For user defined types it
applies what you say.


So lets state:
++u is never slower.

Now it's perfect ;P


Unless ofcourse I play Devil's Advocate and write my own unique ++u
operator!

-JKop
Jul 22 '05 #11

"The Doctor" <do****@nospam.com> wrote in message
news:Xn**********************************@61.9.191 .5...
| Hi all,
|
| Recently I was asked the question about whether ++U or U++ is
| faster if U is a user defined type. What's the answer?
|
| Thank you

The answer is that it depends on those two operator in the user defined
type. ++U is usually faster.

Does any one know why these two operator are not symmetrical?

UserType& operator++ ( ); // prefix ++
UserType operator++ (int dummy); // postfix ++

Why can't it be:

UserType& operator++ (int dummy); // postfix ++

What is the rational behind this?

Thanks,
Pedro Carvalho

Jul 22 '05 #12
> Does any one know why these two operator are not symmetrical?

UserType& operator++ ( ); // prefix ++
UserType operator++ (int dummy); // postfix ++

Why can't it be:

UserType& operator++ (int dummy); // postfix ++

What is the rational behind this?

Thanks,
Pedro Carvalho

int& Blah()
{
int k = 7;

return k;
}
If you don't see the problem in the above then I'd be surprised that you
know about operator overloading in the first place. (Not an insult, just an
observation.)

But ofcourse, you can always:
int& Blah()
{
return *new int(7);
}

just as long as you call delete down the road...
-JKop

-JKop
Jul 22 '05 #13
"Pedro Miguel Carvalho" <Pe********@sapo.pt> wrote in message
news:41**********************@news.telepac.pt...

"The Doctor" <do****@nospam.com> wrote in message
news:Xn**********************************@61.9.191 .5...
| Hi all,
|
| Recently I was asked the question about whether ++U or U++ is
| faster if U is a user defined type. What's the answer?
|
| Thank you

The answer is that it depends on those two operator in the user defined
type. ++U is usually faster.

Does any one know why these two operator are not symmetrical?

UserType& operator++ ( ); // prefix ++
UserType operator++ (int dummy); // postfix ++

Why can't it be:

UserType& operator++ (int dummy); // postfix ++

What is the rational behind this?


++foo should increment foo and return foo. On the other hand, foo++ should
increment foo and return the value it had before it was incremented. It
should not return a reference to itself, because that would be confusing.
It should not return a reference to another instance of UserType because it
causes the problems described in JKop's post. It simply can't return a
reference without causing complications.

--
David Hilsee
Jul 22 '05 #14
> For built-in types their speed is the same. For user defined types it
applies what you say.


Not necessarily, the architechture could be register starved and ++u might
fit the computation in the ALU registers while ++u might not, on the other
hand this might not have any real-world impact on the performance as the ISA
might be translated dynamically to format the hardware ALU uses internally,
which may result in same transistors having the same inputs in the same
sequence. IA32 is a prime example of architechture where this evaluation has
a good chance of being realized.

Some architechtures even make distinction of post- and pre-
increment/decrement in their binary instructions, think of Motorola 680x0 as
one example. It might make a difference or it might not, that depends on the
context. As far as the programming language c++ is concerned it does appear
to make a difference.
Jul 22 '05 #15
> Why can't it be:

It can be.
What is the rational behind this?


More often than not the other form yields predictable results which is quite
important rational in general.
Jul 22 '05 #16
"David Hilsee" <da*************@yahoo.com> wrote in message
news:Ra********************@comcast.com...
| "Pedro Miguel Carvalho" <Pe********@sapo.pt> wrote in message
| news:41**********************@news.telepac.pt...
| > "The Doctor" <do****@nospam.com> wrote in message
| > news:Xn**********************************@61.9.191 .5...
| > Does any one know why these two operator are not symmetrical?
| >
| > UserType& operator++ ( ); // prefix ++
| > UserType operator++ (int dummy); // postfix ++
| >
| > Why can't it be:
| >
| > UserType& operator++ (int dummy); // postfix ++
| >
| > What is the rational behind this?
|
| ++foo should increment foo and return foo. On the other hand, foo++
should
| increment foo and return the value it had before it was incremented. It
| should not return a reference to itself, because that would be confusing.
| It should not return a reference to another instance of UserType because
it
| causes the problems described in JKop's post. It simply can't return a
| reference without causing complications.

I understand why foo++ must return a copy of the old value if it is executed
at the beginning of the statement.
For example
bar( ++I );
is equivalent to
++I;
bar( I );
and
bar( I++ );
is equivalent to (J is temporary)
J = I++;
bar( J );
My question is why not evaluate I++ after bar() like this
Make
bar( I++ );
equivalent to
bar( I );
I++;

Of course, all this was decided long ago and nothing will be changed now.

Pedro Carvalho

Jul 22 '05 #17
Always use ++u, since they're suposed to be faster.
If you use iterator's then you must allways use ++u.
this is a recommendation from Bjarne Stroustrup book,
see chapter about Iterators

"David Hilsee" <da*************@yahoo.com> wrote in message news:<Ra********************@comcast.com>...
"Pedro Miguel Carvalho" <Pe********@sapo.pt> wrote in message
news:41**********************@news.telepac.pt...

"The Doctor" <do****@nospam.com> wrote in message
news:Xn**********************************@61.9.191 .5...
| Hi all,
|
| Recently I was asked the question about whether ++U or U++ is
| faster if U is a user defined type. What's the answer?
|
| Thank you

The answer is that it depends on those two operator in the user defined
type. ++U is usually faster.

Does any one know why these two operator are not symmetrical?

UserType& operator++ ( ); // prefix ++
UserType operator++ (int dummy); // postfix ++

Why can't it be:

UserType& operator++ (int dummy); // postfix ++

What is the rational behind this?


++foo should increment foo and return foo. On the other hand, foo++ should
increment foo and return the value it had before it was incremented. It
should not return a reference to itself, because that would be confusing.
It should not return a reference to another instance of UserType because it
causes the problems described in JKop's post. It simply can't return a
reference without causing complications.

Jul 22 '05 #18
Method Man wrote:
"The Doctor" <do****@nospam.com> wrote in message
news:Xn**********************************@61.9.191 .5...
Hi all,

Recently I was asked the question about whether ++U or U++ is
faster if U is a user defined type. What's the answer?

Thank you

The simple answer is when using U++, the object U needs to get copied twice
whereas with ++U, it need only be copied once.

So use ++U unless you specifically require the value of the post-increment.


Depends on the compiler's optimizer and how the increment is
used.

For example:
/* 1 */ int i = 6;
/* 2 */ ++i;
/* 3 */ i++;

In the above example, the compiler can translate lines
2 and 3 into simple increment instructions that have no
copy requirements.
--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book

Jul 22 '05 #19
The Doctor wrote:
Hi all,

Recently I was asked the question about whether ++U or U++ is
faster if U is a user defined type. What's the answer?

Thank you


According to the "Effective C++" and "More Effective C++"
books by Scott Meyers, the prefix form (++U) should be
preferred over the postfix version.

As far as speed is concerned, the difference is negligble
depending on how large the type is for U; or how complex
an increment operation is. One should alway profile
the _whole_ program before worrying about efficiency
of one expression or statement.

Profile your own code. If the section that _needs_
optimizing contains the increment operator, have the
compiler print out an assembly language listing of
that section. See how the compiler is translating
the increment. If _you_ can optimize that one statement
better in assembly, then reorganize the source to
provide hints to the compiler. I really doubt that
a person can optimize only the incrementing in assembly
due to the overhead involve in a call to an assembly
language function. A person may be able to optimize
better than the compiler by using inline assembly,
but by this time, you are wasting more time playing
with the compiler than producing code and finishing
the project.

Just pick a preference and stick to it. Worry about
the efficiency after the program works correctly
and is robust. If there is a _need_ for space or
time for optimization, then perform it at the end.
Sometimes, when the program is running extremely
slow or is extremely huge during development, some
optimizations may be necessary. For example, if
an embedded system runs out of execution space
before the integration phase is completed, optimizations
should be performed (such as removing unnecessary
code). But, in general, save optimizations for
after the progam is finished.

Spend your time on a more worthwhile endeavor,
such as making the code more readable.

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book

Jul 22 '05 #20
"Filipe Valepereiro" <ef***@portugalmail.pt> wrote in message
news:2f**************************@posting.google.c om...
Always use ++u, since they're suposed to be faster.
If you use iterator's then you must allways use ++u.
this is a recommendation from Bjarne Stroustrup book,
see chapter about Iterators

<snip>

If you're referring to the "advice" section, then let me point out that he
wisely uses the word "prefer" and not "always". In certain cases, favoring
preincrement leads to awkward code that isn't necessarily more efficient.
If you're going to wind up writing

SomeIterator tmp(i);
++i;
doSomething(tmp);
// no other usage of tmp after this

then you might as well write

doSomething( i++ );

This type of code most often occurs when iterating over certain containers
and erasing elements as you go.

--
David Hilsee
Jul 22 '05 #21
"Pedro Miguel Carvalho" <Pe********@sapo.pt> wrote in message
news:41***********************@news.telepac.pt...
<snip>
I understand why foo++ must return a copy of the old value if it is executed at the beginning of the statement.
For example
bar( ++I );
is equivalent to
++I;
bar( I );
and
bar( I++ );
is equivalent to (J is temporary)
J = I++;
bar( J );
My question is why not evaluate I++ after bar() like this
Make
bar( I++ );
equivalent to
bar( I );
I++;

Of course, all this was decided long ago and nothing will be changed now.


That would make the operator behave differently from everything else. When
the programmer writes

bar( doSomething() );

that's supposed to mean that doSomething() executes, and its result is
passed to bar. Making the operator a special case would be confusing, IMHO,
especially if bar could determine the value of I (say, via a pointer). But
yes, all of this was decided long ago.

--
David Hilsee
Jul 22 '05 #22
I couldn't understand the below sentence because I can't tell which of
the below should read u++ - could you fix it as I would really like to
keep my code efficient.

Plus, are you talking about built in types (eg int) or classes here?

On Mon, 27 Sep 2004 12:37:07 +0300, "assaarpa" <re***********@fap.net>
wrotE:
Not necessarily, the architechture could be register starved and ++u might
fit the computation in the ALU registers while ++u might not.

Jul 22 '05 #23

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

36
by: Armin Rigo | last post by:
Hi! This is a rant against the optimization trend of the Python interpreter. Sorting a list of 100000 integers in random order takes: * 0.75 seconds in Python 2.1 * 0.51 seconds in Python...
23
by: YinTat | last post by:
Hi, I learned C++ recently and I made a string class. A code example is this: class CString { public: inline CString(const char *rhs) { m_size = strlen(rhs);
98
by: jrefactors | last post by:
I heard people saying prefix increment is faster than postfix incerement, but I don't know what's the difference. They both are i = i+1. i++ ++i Please advise. thanks!!
65
by: Skybuck Flying | last post by:
Hi, I needed a method to determine if a point was on a line segment in 2D. So I googled for some help and so far I have evaluated two methods. The first method was only a formula, the second...
1
by: James dean | last post by:
I done a test and i really do not know the reason why a jagged array who has the same number of elements as a multidimensional array is faster here is my test. I assign a value and do a small...
9
by: VenuGopal | last post by:
Hi, why n++ executes faster than n+1..... or does it realli execute faster? thanks Venugopal.B
11
by: ctman770 | last post by:
Hi Everyone, Is it faster to save the precise location of an html dom node into a variable in js, or to use getElementById everytime you need to access the node? I want to make my application...
12
by: karthikbalaguru | last post by:
Hi, How is 'Int' Faster than 'Char' ? I think , 'Char' is small and so it should be easily & efficiently . Can someone here provide some info regarding this. Thanks and Regards, Karthik...
23
by: Python Maniac | last post by:
I am new to Python however I would like some feedback from those who know more about Python than I do at this time. def scrambleLine(line): s = '' for c in line: s += chr(ord(c) | 0x80)...
41
by: c | last post by:
Hi every one, Me and my Cousin were talking about C and C#, I love C and he loves C#..and were talking C is ...blah blah...C# is Blah Blah ...etc and then we decided to write a program that...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.