473,236 Members | 1,808 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,236 software developers and data experts.

(General Query) why n++ executes faster than n+1

Hi,
why n++ executes faster than n+1..... or does it realli execute faster?

thanks
Venugopal.B
Nov 17 '05 #1
9 5136
VenuGopal <Ve*******@discussions.microsoft.com> wrote:
why n++ executes faster than n+1..... or does it realli execute faster?


I assume that you mean to ask:

| If n is an int, does
| n++;
| execute faster than
| n = n + 1;
| ?

The answer to the above is: no. Both statements compile down to the exact
same IL instructions.
Nov 17 '05 #2
n++ just types faster...
--
David Anton
www.tangiblesoftwaresolutions.com
Home of:
Clear VB: Cleans up outdated VB.NET code
Instant C#: Converts from VB.NET to C#
Instant VB: Converts from C# to VB.NET
Instant J#: Converts from VB.NET to J#
"VenuGopal" wrote:
Hi,
why n++ executes faster than n+1..... or does it realli execute faster?

thanks
Venugopal.B

Nov 17 '05 #3
I have heard interview questions about why would ++n executes faster
than n++?
The prefix operator will always be faster than the postfix. The postfix
version involves a copy and internal call to the prefix. For simple
types the relative cost between the two should be small. For more
complicated objects (e.g. iterating over a vector) the cost may be
larger. The general consensus in C++ literature (More Exceptional C++,
More Effective C++) is that the prefix version should always be
preferred. Doing this you cannot go wrong. In addition, writing ++
instead of ++ costs nothing.

Nov 17 '05 #4


bo*********@gmail.com wrote:
I have heard interview questions about why would ++n executes faster
than n++?
I think they would need a new CTO ;)
The prefix operator will always be faster than the postfix.
No, (with standard side-effect perception) the postfix can never be
faster than the prefix. There is a difference.
The postfix
version involves a copy and internal call to the prefix. For simple
types the relative cost between the two should be small.
None. look at the optimized code.
For more
complicated objects (e.g. iterating over a vector) the cost may be
larger.
No, std::vector::(const_)iterator is usually implemented by classes that
compiles and optimizes down to pointers. Look at the optimized code.
The general consensus in C++ literature (More Exceptional C++,
More Effective C++) is that the prefix version should always be
preferred. Doing this you cannot go wrong. In addition, writing ++
instead of ++ costs nothing.


If you "optimize" your programs by writing "++x" instead of "x++" you
are doing something wrong. ++x and x++ have different semantics and you
should choose the one that fits, not the one you think is fastest.
Should you feel tempted to replace the statement "x = x + 1;" with
something else, you should use "++x;" since you don't care about the
side-effect of "x++", which *may* cost you something.

Even *if* you call the x++ operator, and it's implemented using copying
chances are the optimizer will still be able to remove that copying
because the returned object is unused.

In C# there are other reasons to think before using x++, for example x++
on C# defined class'es compiles but still gives you ++x, even if you
only implemented ++x!

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #5
Inline

On 8/28/05, Helge Jensen <he**********@slog.dk> wrote:


bo*********@gmail.com wrote:
I have heard interview questions about why would ++n executes faster
than n++?
I think they would need a new CTO ;)
The prefix operator will always be faster than the postfix.


No, (with standard side-effect perception) the postfix can never be
faster than the prefix. There is a difference.


I said, "The prefix operator will always be faster than the postfix."
You said, "postfix can never be faster than the prefix. There is a
difference."
I totally didn't get this. Aren't we saying the same thing?
The postfix
version involves a copy and internal call to the prefix. For simple
types the relative cost between the two should be small.


None. look at the optimized code.

So if I did
"return ++x; " instead of "return x++;" in my function, you mean to
say that the assembly code generates the same number of instructions?
What about the copy for the postfix.....
For more
complicated objects (e.g. iterating over a vector) the cost may be
larger.
No, std::vector::(const_)iterator is usually implemented by classes that
compiles and optimizes down to pointers. Look at the optimized code.


What about the copy for the postfix? And if you custom implemented a
class called Money and had a prefix and postfix operation defined for
it. The implementation of postfix and prefix would be the same code???
The general consensus in C++ literature (More Exceptional C++,
More Effective C++) is that the prefix version should always be
preferred. Doing this you cannot go wrong. In addition, writing ++
instead of ++ costs nothing.
If you "optimize" your programs by writing "++x" instead of "x++" you
are doing something wrong. ++x and x++ have different semantics and you
should choose the one that fits, not the one you think is fastest.

Yes, I understand that the semantic is different and it should be used
on a case by case bases.


Should you feel tempted to replace the statement "x = x + 1;" with
something else, you should use "++x;" since you don't care about the
side-effect of "x++", which *may* cost you something.

Even *if* you call the x++ operator, and it's implemented using copying
chances are the optimizer will still be able to remove that copying
because the returned object is unused.

In C# there are other reasons to think before using x++, for example x++
on C# defined class'es compiles but still gives you ++x, even if you
only implemented ++x!

Sorry, I didn't understand the above statement.
I am trying to understand your arguments and trying to make it clear
for my own understanding. Please explain. Thanks!
Sincerely,
Bobby

Nov 17 '05 #6
Hi
The best is to look at IL code which is generated from the both.But i
think it should not be a great difference or probably no difference.

Shivprasad Koirala
C# , VB.NET , SQL SERVER , ASP.NET Interview Questions
http://www.geocities.com/dotnetinterviews/

Nov 17 '05 #7
bo*********@gmail.com <bo*********@gmail.com> wrote:
The prefix operator will always be faster than the postfix.


No, (with standard side-effect perception) the postfix can never be
faster than the prefix. There is a difference.


I said, "The prefix operator will always be faster than the postfix."
You said, "postfix can never be faster than the prefix. There is a
difference."
I totally didn't get this. Aren't we saying the same thing?


Absolutely not!

The difference is that in the common case, where it's a statement on
its own, both versions compile to the same code - so the performance is
the same.

That contradicts your statement, but doesn't contradict Helge's.
The postfix
version involves a copy and internal call to the prefix. For simple
types the relative cost between the two should be small.


None. look at the optimized code.


So if I did
"return ++x; " instead of "return x++;" in my function, you mean to
say that the assembly code generates the same number of instructions?
What about the copy for the postfix.....


Actually, if x is a local variable of a simple type, I'd expect
return x++;
to actually be faster than
return ++x;

because it would be equivalent to:
return x;

No addition would actually be necessary at all.

(This actually violates Helge's assertion that postfix can never be
faster than the prefix, but I suspect he means in the situation where
the increment is actually required.)

<snip>

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #8
bo*********@gmail.com wrote:
No, (with standard side-effect perception) the postfix can never be
faster than the prefix. There is a difference. I said, "The prefix operator will always be faster than the postfix."
You said, "postfix can never be faster than the prefix. There is a
difference."
I totally didn't get this. Aren't we saying the same thing?


Faster is a strict ordering. You are saying time(prefix) <
time(postfix), im saying time(postfix) >= time(prefix).

Further down the post, I claim that time(postfix) == time(prefix) for
most defined (properly written) ++-operators, so it really doesn't
matter much.

I *know* that ++x *may* be better than x++, and write "++it" myself in
C++ programs, but it's not really essential.

If you think you are "optimizing" by using ++x instead of x++, i claim
something is wrong and that you should spend your time looking at
somewhere else in the program -- like where the profiler shows that the
time is spent ;)
The postfix
version involves a copy and internal call to the prefix. For simple
types the relative cost between the two should be small.


None. look at the optimized code.


So if I did
"return ++x; " instead of "return x++;" in my function, you mean to
say that the assembly code generates the same number of instructions?
What about the copy for the postfix.....


There will be no copy, it will be optimzed away, since the copy is
unused. Compilers are *good* at this game! If you don't believe me, try
and have a look at some optimized code.
For more
complicated objects (e.g. iterating over a vector) the cost may be
larger.


No, std::vector::(const_)iterator is usually implemented by classes that
compiles and optimizes down to pointers. Look at the optimized code.

What about the copy for the postfix? And if you custom implemented a


If the copy is not used it will (most probably, with current C++
compilers) never be produced. This is especially *very* likely if the
"copy" is just a copy of a pointer.
class called Money and had a prefix and postfix operation defined for
it. The implementation of postfix and prefix would be the same code???
No, but that part that creates the code will produce data that is
unused. The compiler will find this out and remove the construction of
that data.

In C#, the code for pre- and postfix-++ will *actually* be the same
code. There is no way to declare a postfix++ in C#. Only what is
returned differs (depending on how you read §14.5.9 in ISO/IEC
23270:2003(E)).
In C# there are other reasons to think before using x++, for example x++
on C# defined class'es compiles but still gives you ++x, even if you
only implemented ++x!

Sorry, I didn't understand the above statement.
It is unclear to me *exactly* how overloaded postfix operations occur.
The C# languages specification, §14.5.9: Postfix increment and decrement
operators. uses the word "saved" to define postfix operations. "save"
only occurs 8 times in ISO/IEC 23270:2003(E), 7 of which are in the
definition of operators, and it's meaning is never defined.

The current Visual C# implements "saved" so that you get the expected
result -- even on reference-types. How this is done i really can't guess
at this time. I speculate that there is a nasty bug somewhere inside all
this, since the Visual C# definition efficiently requires "save" to
clone objects. I will have to write a test-program someday.

The standard isn't clear on the exact semantics of postfix++. My
interpretation of §14.5.9 would certainly *not* lead to the
implementation in Visual C#.
I am trying to understand your arguments and trying to make it clear
for my own understanding. Please explain. Thanks!


I hope this helps.

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #9


Jon Skeet [C# MVP] wrote:
Actually, if x is a local variable of a simple type, I'd expect
return x++;
to actually be faster than
return ++x;

because it would be equivalent to:
return x;
aaargh, stop this "optimization" madness!
(This actually violates Helge's assertion that postfix can never be
faster than the prefix, but I suspect he means in the situation where
the increment is actually required.)


haha, very funny.

If the calling code does not depend on the returned value (which we may
assume since it is semantic equivalent to sustitute x++ for ++x) the
increment on x will probably not be performed in either case, if the
function is inlined... the returned value is not used, and operations on
it without sideeffects are probably optimized out :)

--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #10

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

Similar topics

8
by: Rob Ristroph | last post by:
I have tried out PHP 5 for the first time (with assistance from this group -- thanks!). The people I was working with have a site that uses lots of php objects. They are having problems with...
2
by: vidya | last post by:
Hi, I wrote a stored procdure in SQL Server which calculates some metrics. This procedure always returns only one row with 11 columns of integer values. I ran it in SQL Server Query Analyzer...
0
by: Robert Wille | last post by:
I have a number of very common queries that the optimizer plans a very inefficient plan for. I am using postgres 7.2.3. I vacuum hourly. I'm wonderingwhat I can do to make the queries faster. Here...
1
by: Robert Wille | last post by:
I have a number of very common queries that the optimizer plans a very inefficient plan for. I am using postgres 7.2.3. I vacuum hourly. I'm wonderingwhat I can do to make the queries faster. Here...
2
by: ruben | last post by:
Hi: I must have missed something, but how is it possible that a join on tables A and B is faster (a lot faster) than a query to one of the tables with the same conditions? The problem seems...
2
by: Great_milenko | last post by:
I've made a form that when it saves executes a tablecreate_query, because this table already excists and has to to be ovewritten it gives a prompt message that it deletes the table, my question now...
10
by: Raj | last post by:
I have an MDC index on Big_A.Dt column. The following query always goes for a table scan. SELECT Key, Cd, Dt, SUM(Big_A ) FROM ( SELECT Big_A.Key , small_3.Cd,
4
by: Andrus | last post by:
DLinq objects: class Item { string ItemCode {get;set;} // primary key } class Stock { // primary key is (ItemCode,StockId) string ItemCode {get;set;} string Quantity { get; set; } string...
16
by: pabs1111 | last post by:
I'm trying to filter the records in a form using a pass through query. strFilter = strFilter & "( eventid in (select FWIPEvent.eventid from FWIPEvent )) " Me.Filter = strFilter Me.FilterOn =...
0
by: jianzs | last post by:
Introduction Cloud-native applications are conventionally identified as those designed and nurtured on cloud infrastructure. Such applications, rooted in cloud technologies, skillfully benefit from...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

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.