Is
faster thanCode:++x;
? I thought it might be, since ++x can do the increment right then and there, while x++ has to do it later.Code:x++;
Printable View
Is
faster thanCode:++x;
? I thought it might be, since ++x can do the increment right then and there, while x++ has to do it later.Code:x++;
gcc seems to use the same number of instructions for both. I tested with the following 2 programs:
Then I compiled each with: gcc -S <filename>Code:itsme@itsme:~/C$ cat prefix.c
int main(void) { int i = 0; int j; j = ++i; }
itsme@itsme:~/C$ cat postfix.c
int main(void) { int i = 0; int j; j = i++; }
I won't spam the post by actually pasting the entire .s files, but only a few lines changed, and I'll post those:
Code:// prefix.s
leal -4(%ebp), %eax
incl (%eax)
movl -4(%ebp), %eax
Those lines are in the same place as they are in the other file, so there's the same number of instuctions. The rest of the instructions are exactly the same.Code:// postfix.s
movl -4(%ebp), %edx
leal -4(%ebp), %eax
incl (%eax)
Hmm, okay, thanks for going to so much trouble.
You'll find that prefix is faster than postfix for some non-primitive datatypes in C++. (Yes I know this is the C forum.)
:)Quote:
Originally Posted by dwks
Code:gcc -S some_prog.c
I know, that's why I was wondering if prefix was faster for ints too.Quote:
prefix is faster than postfix for some non-primitive datatypes in C++
The only real guarantee is that prefix will be no slower than postfix.
In principle, x++ (for x an int) must be expanded to something like;
while ++x requires no temporary storage of the original value of x. A literal interpretation of that requirement would make postfix slower than prefix operations.Code:int temp = x;
x = x+1;
/* allow value of temp to be accessible */
However, compilers (or, more accurately, compiler writers) are smarter than that. Most mainstream compilers are able to recognise cases where the original value of x need not be accessible, and therefore avoid storing it's value temporarily. Which is the reason that the example given by itsme86 will usually exhibit no measurable difference in terms of number of instructions or performance.