Register Relation

Why p++ is faster than p+1?

Questions by akshay201989

Editorial / Best Answer

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
add bx
mov,
ax

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

Showing Answers 1 - 0 of 0 Answers

tewari2312

  • 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

  Was this answer useful?  Yes

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
add bx
mov,
ax


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

yzesong

  • 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.

  Was this answer useful?  Yes

AlexeyP

  • 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.

arunv111285

  • 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).

  Was this answer useful?  Yes

Gargona

  • 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
-       addl    $1, -4(%ebp)
        leave
        ret
        .size   main, .-main
--

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions