Register Relation

Why p++ is faster than p+1?

sahasranaman

• Member Since Jul-2009 | Jul 1st, 2009

p++ is faster because on compilation, it gets translated to three machine instructions, where as p=p+1 needs four machine instructions. All machine instructions take the same time.

For p++, the instructions are:
mov ax,
inc ax
mov,
ax

For p = p+ 1, the instructions would be,
mov ax,
mov bx, 1
mov,
ax

This is why p++ is faster than p+1

• May 29th, 2009

I don't think  p+1 is faster than p++.
Internally P++ will be implemented as P+1 only.
Although the ++P is faster than P++ as it avoids the temporary variable creation.

• Jun 13th, 2009

p++
when the command p++ is given the compiler understands that value of p is incresed by one and wherever p is used (as in the expression u=p/2) it(compiler) uses value p+1rather than p, so
if the code is
int p;
p++;
float u=p/2;
then the lines compiler understands is
int p;
p++;
float u=(p+1)/2;

p=p+1
when this statement is written then the compiler goes to the location where p is stored and increments the value by 1

• Jul 1st, 2009

p++ is faster because on compilation, it gets translated to three machine
instructions, where as p=p+1 needs four machine instructions. All machine
instructions take the same time.

For p++, the instructions are:
mov ax,
inc ax
mov,
ax

For p = p+ 1, the instructions would be,
mov ax,
mov bx, 1
mov,
ax

This is why p++ is faster than p+1

• Jul 15th, 2009

I agree with sahasranaman. When you look at assembly level, P++ take less instructions than P+1, so P++ is faster, I think P++ and ++P are the same.

• Jul 21st, 2009

Becuase it is a unary operator

• Oct 8th, 2009

I think P++ and ++P are the same

No, not the same.

For P++ you have to save value in a temp, increment *this, then return the saved value.

For ++P, you just increment and return -- less work.

• Feb 10th, 2010

p++ is actually slower than p+1 since in this case there is no change in the value of p. In case of p++, two values of p are to be maintained (value of p before and after incrementing).

• Feb 13th, 2010

Difference in assembler code:

--
\$ diff -uN a2.S a.S
--- ++p.S        2010-02-13 15:51:09.000000000 +0200
+++ p+1.S 2010-02-13 15:50:30.000000000 +0200
@@ -6,7 +6,6 @@
pushl   %ebp
movl    %esp, %ebp
subl    \$16, %esp
leave
ret
.size   main, .-main
--

Mann2920 Profile Answers by Mann2920 Questions by Mann2920

• Jan 24th, 2011

To perform i+1 complier has to do:

While in case of i++
Value is simply increased by 1

so i++ is faster