473,320 Members | 2,048 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,320 software developers and data experts.

i++ and ++i

I know that one of them is efficient. But dont know which one of them.
Can someone explain me which one of them is efficient and why?

Thanks in advance.

Jul 27 '06 #1
13 2605

jsshah wrote:
I know that one of them is efficient.
Then you know wrong. Neither (or both, for that matter) are effecient.
But dont know which one of them.
Can someone explain me which one of them is efficient and why?
Nope. No one can explain to you which one is effecient.

Someone here will, no doubt, explain to you why you have asked a
nonsense (wrt C) question. I hope you read their answer.

--
Lew Pitcher

Jul 27 '06 #2
Lew Pitcher <lp******@sympatico.cawrote:

(WRT ++i vs. i++ being "efficient")
Then you know wrong. Neither (or both, for that matter) are effecient.
Someone here will, no doubt, explain to you why you have asked a
nonsense (wrt C) question. I hope you read their answer.
I think this is unnecessarily harsh on OP, who seems to have simply
neglected to include the word "more" in his or her query. I think the
"it depends on your implementation" answer would have been more
appropriate, or at the least more helpful and informative. Then
again, perhaps the "STFW" answer would have been ideal, that is both
snarky and potentially helpful.

--
C. Benson Manica | I *should* know what I'm talking about - if I
cbmanica(at)gmail.com | don't, I need to know. Flames welcome.
Jul 27 '06 #3

jsshah wrote:
I know that one of them is efficient. But dont know which one of them.
Can someone explain me which one of them is efficient and why?
I suppose it's possible for an implementation to execute one form more
efficiently than the other. You would need to look at the assembler
output for the two cases. One might image that it *could* be easier for
the compiler to generate fewer instructions for ++i than i++ but I'd be
surprised if modern compilers couldn't detect either idiom and do the
smart thing in both cases.
--
- Mark

Jul 27 '06 #4
>I know that one of them is efficient. But dont know which one of them.
>Can someone explain me which one of them is efficient and why?
>I suppose it's possible for an implementation to execute one form more
efficiently than the other. You would need to look at the assembler
output for the two cases.
C mandates nothing about the "efficiency" of implementation, therefore
in a given C implementation, either operation may result in anything from
a single increment instruction for a given usage to a call to multiple
nested subroutines (unlikely but possble). And this could change with the
exact usage. - A different implementation may do the reverse, generate
one code sequence for one form, and a completely different code sequence
for another form. Examining the assembly output of a compiler may give you
a hint as to which is more efficient for that particular compiler and usage,
however it will tell you nothing about the general nature of the operations
(ie: any results you get will be highly compiler/platform/use dependant).

As most of us know (but just in case the OP doesn't) , these are not
the same operator:

++i evaluates to (i+1) with the side effect of incrementing i (in other
words - returns the value of I AFTER the increment)

i++ evaluates to (i) with the side effect of incrementing i (in other
words - return the value of I BEFORE the increment)

One may be more "efficient" than the other in a particular algorithm,
(for example using ++i in a case where you need the preincremented
value means either using (i-1) later, or another variable) - however
even in this case, most compilers will optimize the results to the same
or equivalent code - And who knows - some perverse architecture
could exist where the opposite of "what you expect" in terms of
efficiency is true. The point I am making is that you really cannot
make a correlation between individual C operations (or even groups
of operations) and efficiency. Write clean readable straightforward
code and trust the compiler to do it's job.

>One might image that it *could* be easier for
the compiler to generate fewer instructions for ++i than i++ but I'd be
surprised if modern compilers couldn't detect either idiom and do the
smart thing in both cases.
This caught my eye (and is the main reason I responded) ... In very
early versions of my compiler, for certain register limited architectures,
i++ could generate
load i
increment
store i
decrement

And the compiler wasn't bright enough to recognize those operations
which were being performed for the side effect only, resulting in
extra an unneeded "decrement" operations when i++ was used
independantly, but not when ++i was used.

This artifact is long gone, and both operations will produce exactly the
same code in all architectures I support now - but it does provide a
real example of how one CAN be more efficient that the other IN A
GIVEN IMPLEMENTATION. The problem is there are no rules that
you can use to determine this.

When you are using these operations for the side effect only, it really
comes down to a matter of personal taste/style. Partly because of the
behaviour of my early compilers described above, but mostly because
I think "increment i" and not "i gets incremented", I code ++i instead of
i++ ... but I would not expect either to consistantly produce more efficient
(or even different) code than the other.

Regards,

--
Dunfield Development Services http://www.dunfield.com
Low cost software development tools for embedded systems
Software/firmware development services Fax:613-256-5821

Jul 27 '06 #5
On 2006-07-27, Christopher Benson-Manica <at***@ukato.freeshell.orgwrote:
Lew Pitcher <lp******@sympatico.cawrote:

(WRT ++i vs. i++ being "efficient")
>Then you know wrong. Neither (or both, for that matter) are effecient.
>Someone here will, no doubt, explain to you why you have asked a
nonsense (wrt C) question. I hope you read their answer.

I think this is unnecessarily harsh on OP, who seems to have simply
neglected to include the word "more" in his or her query. I think the
"it depends on your implementation" answer would have been more
appropriate, or at the least more helpful and informative. Then
again, perhaps the "STFW" answer would have been ideal, that is both
snarky and potentially helpful.
Uhm, I can't think of an implementation where the two of those would
have different opcode sequences, let alone a difference in speed. It
can be said with 99.99995% certainty that neither of them is faster
than the other by a meaningful amount.

--
Andrew Poelstra <website down>
To reach my email, use <email also down>
New server ETA: 2 days
Jul 27 '06 #6
jsshah wrote:
I know that one of them is efficient. But dont know which one of them.
Can someone explain me which one of them is efficient and why?
Maybe you are thinking of C++ where pre-increment is generally faster
for user defined types. For PODs there probably isn't any difference.

--
Ian Collins.
Jul 27 '06 #7
Andrew Poelstra <ap*******@localhost.localdomainwrites:
On 2006-07-27, Christopher Benson-Manica <at***@ukato.freeshell.orgwrote:
>Lew Pitcher <lp******@sympatico.cawrote:

(WRT ++i vs. i++ being "efficient")
>>Then you know wrong. Neither (or both, for that matter) are effecient.
>>Someone here will, no doubt, explain to you why you have asked a
nonsense (wrt C) question. I hope you read their answer.

I think this is unnecessarily harsh on OP, who seems to have simply
neglected to include the word "more" in his or her query. I think the
"it depends on your implementation" answer would have been more
appropriate, or at the least more helpful and informative. Then
again, perhaps the "STFW" answer would have been ideal, that is both
snarky and potentially helpful.

Uhm, I can't think of an implementation where the two of those would
have different opcode sequences, let alone a difference in speed. It
can be said with 99.99995% certainty that neither of them is faster
than the other by a meaningful amount.
I think you're assuming that they're being used in a statement
context. For example, I'd (almost) certainly expect identical code
for these two statements:

i++;
++i;

But if they're used in a larger expression:

j = i++;
j = ++i;

then they mean different things, and of course you'll get different
code for them. (Which is more efficient is a different question, and
one that the language doesn't answer.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jul 27 '06 #8
jsshah posted:
I know that one of them is efficient. But dont know which one of them.
Can someone explain me which one of them is efficient and why?

The C programming language is intended for writing programs for a wide
variety of systems.

These different systems do things differently internally, and so some
things may be less or more efficient on different systems.

A good example would be the portable way to copy a string:

Example (1)

void CpyStr(char *dest,char const *source)
{
for ( ; *dest++ = *source++; );
}

Example (2)

void CpyStr(char *dest,char const *source)
{
while ( ; *dest = *source; ++dest,++source);
}

At first glance, Example (2) would appear to be more efficient, as it
doesn't perform an extra redundant incrementation. However, consider if
you're working on a system where the following two activities can be
performed in one sole CPU instruction:

(1) Retrieve the data pointed at by a pointer.
(2) Increment the pointer.

On such a system, Example (1) would certainly be more efficient, even
though it performs an extra redundant incrementation. (There are such
systems which can do this in one instruction).

As for your question of "i++" Vs. "++i", well I've a couple of things to
say:

(1) Either might be more efficient, depending on the system.
(2) When your compiler sees the expression on its own, and realises that
the value of the expression is discarded, then it may simply use the more
efficient one.
(3) I myself favour pre-incrementation wherever possible, i.e. "++i", as
it's the most simple one to get the job done, and its functionality
coincides with that of the other operators such as "=", "+=", "-=", "&=".

You'll see many people use "i++" where "++i" would suffice. It's just their
style. I have my own style, and I use "++i".

--

Frederick Gotham
Jul 27 '06 #9
Frederick Gotham wrote:
jsshah posted:
>I know that one of them is efficient. But dont know which one of them.
Can someone explain me which one of them is efficient and why?


The C programming language is intended for writing programs for a wide
variety of systems.

These different systems do things differently internally, and so some
things may be less or more efficient on different systems.

A good example would be the portable way to copy a string:

Example (1)

void CpyStr(char *dest,char const *source)
{
for ( ; *dest++ = *source++; );
}

Example (2)

void CpyStr(char *dest,char const *source)
{
while ( ; *dest = *source; ++dest,++source);
}

At first glance, Example (2) would appear to be more efficient, as it
doesn't perform an extra redundant incrementation. However, consider if
you're working on a system where the following two activities can be
performed in one sole CPU instruction:

(1) Retrieve the data pointed at by a pointer.
(2) Increment the pointer.

On such a system, Example (1) would certainly be more efficient,
That depends on the compiler: I can see that a compiler might compile (2)
as though it were (1), or as peephole optimisation transform

ldr r0, [r1]
add r1, r1, #1
into
ldr r0, [r1, #1]!
even
though it performs an extra redundant incrementation. (There are such
systems which can do this in one instruction).

As for your question of "i++" Vs. "++i", well I've a couple of things to
say:

(1) Either might be more efficient, depending on the system.
(2) When your compiler sees the expression on its own, and realises that
the value of the expression is discarded, then it may simply use the more
efficient one.
(3) I myself favour pre-incrementation wherever possible, i.e. "++i", as
it's the most simple one to get the job done,
? It's as simple as i++, surely.
and its functionality
coincides with that of the other operators such as "=", "+=", "-=", "&=".

You'll see many people use "i++" where "++i" would suffice.
"Suffice" suggests that i++ does something ++i doesn't.
It's just their
style. I have my own style, and I use "++i".
My style twitch is using `i += 1` when the result will be discarded.

--
Chris "seeker" Dollin
"The path to the web becomes deeper and wider" - October Project

Jul 27 '06 #10

jsshah wrote:
I know that one of them is efficient. But dont know which one of them.
Can someone explain me which one of them is efficient and why?

Thanks in advance.
As standalone expression in statements like

i++;
for(i = 0; i < MAX; ++i) ...
while(--i) ...
if (i++) ...

the two forms should result in the same operations (and therefore be
equally efficient). As parts of larger expressions, they may not
result in the same operations, but those differences shouldn't be
significant over a wide range of expressions.

Finally, it doesn't really matter which is more efficient, because
you're ultimately going to use the form that gives the result you need.
For example, think of a simple array-based stack:

#define STACK_SIZE ...
static int sp = STACK_SIZE; // stack pointer
static int stack[STACK_SIZE];
...
void push(int val)
{
if (sp)
stack[--sp] = val; // subtract 1 from sp, save val to this
location
else
/* stack overflow error */
}

int pop(void)
{
if (sp < STACK_SIZE)
return stack[sp++]; // return val from stack[sp], add one
to sp
else
/* stack underflow error */
}

The choice of the prefix or postfix form is driven by how the algorithm
works, not by which one is more efficient.

Jul 27 '06 #11
On 2006-07-27, Keith Thompson <ks***@mib.orgwrote:
Andrew Poelstra <ap*******@localhost.localdomainwrites:
>On 2006-07-27, Christopher Benson-Manica <at***@ukato.freeshell.orgwrote:
>>Lew Pitcher <lp******@sympatico.cawrote:

(WRT ++i vs. i++ being "efficient")

Then you know wrong. Neither (or both, for that matter) are effecient.

Someone here will, no doubt, explain to you why you have asked a
nonsense (wrt C) question. I hope you read their answer.

I think this is unnecessarily harsh on OP, who seems to have simply
neglected to include the word "more" in his or her query. I think the
"it depends on your implementation" answer would have been more
appropriate, or at the least more helpful and informative. Then
again, perhaps the "STFW" answer would have been ideal, that is both
snarky and potentially helpful.

Uhm, I can't think of an implementation where the two of those would
have different opcode sequences, let alone a difference in speed. It
can be said with 99.99995% certainty that neither of them is faster
than the other by a meaningful amount.

I think you're assuming that they're being used in a statement
context. For example, I'd (almost) certainly expect identical code
for these two statements:

i++;
++i;

But if they're used in a larger expression:

j = i++;
j = ++i;

then they mean different things, and of course you'll get different
code for them. (Which is more efficient is a different question, and
one that the language doesn't answer.)
1) Technically, they both increment i and store i in j, although they
do so in different ordered. I can think of contexts where one might
lend itself to additional optimization, but otherwise I can't think
of a situation where they'd be compiled differently.
2) Even if one is faster, the chances of it being a worthy optimization
(as opposed to a style decision) are very slim.

Those two, and this is getting pretty OT.

--
Andrew Poelstra <website down>
To reach my email, use <email also down>
New server ETA: 2 days
Jul 27 '06 #12
"jsshah" <ja******@gmail.comwrote in message
news:11**********************@m79g2000cwm.googlegr oups.com...
I know that one of them is efficient. But dont know which one of
them.
Can someone explain me which one of them is efficient and why?
C itself makes no claim about efficiency; that's an implementation
detail.

On ancient compilers running on ancient computers, ++i was often
slightly faster than i++. However, with a modern optimizing compiler
on a modern OoO machine, there should be no measurable difference
between the two -- and what little difference there may be will vary
depending on context.

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking

--
Posted via a free Usenet account from http://www.teranews.com

Jul 27 '06 #13
"John Bode" <jo*******@my-deja.comwrites:
jsshah wrote:
>I know that one of them is efficient. But dont know which one of them.
Can someone explain me which one of them is efficient and why?

Thanks in advance.

As standalone expression in statements like

i++;
for(i = 0; i < MAX; ++i) ...
while(--i) ...
if (i++) ...

the two forms should result in the same operations (and therefore be
equally efficient). As parts of larger expressions, they may not
result in the same operations, but those differences shouldn't be
significant over a wide range of expressions.
Your last two examples aren't standalone expressions. The result of
the expression is used as a condition, so there's a semantic
difference between the prefix and postfix forms.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jul 27 '06 #14

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

Similar topics

3
by: William C. White | last post by:
Does anyone know of a way to use PHP /w Authorize.net AIM without using cURL? Our website is hosted on a shared drive and the webhost company doesn't installed additional software (such as cURL)...
2
by: Albert Ahtenberg | last post by:
Hello, I don't know if it is only me but I was sure that header("Location:url") redirects the browser instantly to URL, or at least stops the execution of the code. But appearantely it continues...
3
by: James | last post by:
Hi, I have a form with 2 fields. 'A' 'B' The user completes one of the fields and the form is submitted. On the results page I want to run a query, but this will change subject to which...
0
by: Ollivier Robert | last post by:
Hello, I'm trying to link PHP with Oracle 9.2.0/OCI8 with gcc 3.2.3 on a Solaris9 system. The link succeeds but everytime I try to run php, I get a SEGV from inside the libcnltsh.so library. ...
1
by: Richard Galli | last post by:
I want viewers to compare state laws on a single subject. Imagine a three-column table with a drop-down box on the top. A viewer selects a state from the list, and that state's text fills the...
4
by: Albert Ahtenberg | last post by:
Hello, I have two questions. 1. When the user presses the back button and returns to a form he filled the form is reseted. How do I leave there the values he inserted? 2. When the...
1
by: inderjit S Gabrie | last post by:
Hi all Here is the scenerio ...is it possibly to do this... i am getting valid course dates output on to a web which i have designed ....all is okay so far , look at the following web url ...
2
by: Jack | last post by:
Hi All, What is the PHP equivilent of Oracle bind variables in a SQL statement, e.g. select x from y where z=:parameter Which in asp/jsp would be followed by some statements to bind a value...
3
by: Sandwick | last post by:
I am trying to change the size of a drawing so they are all 3x3. the script below is what i was trying to use to cut it in half ... I get errors. I can display the normal picture but not the...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.