Why does n++ execute faster than n=n+1?

user319824 picture user319824 · May 21, 2010 · Viewed 17.5k times · Source

In C language, Why does n++ execute faster than n=n+1?

(int n=...;  n++;)
(int n=...;  n=n+1;)

Our instructor asked that question in today's class. (this is not homework)

Answer

Betamoo picture Betamoo · May 21, 2010

That would be true if you are working on a "stone-age" compiler...

In case of "stone-age":
++n is faster than n++ is faster than n=n+1
Machine usually have increment x as well as add const to x

  • In case of n++, you will have 2 memory access only (read n, inc n, write n )
  • In case of n=n+1, you will have 3 memory access (read n, read const, add n and const, write n)

But today's compiler will automatically convert n=n+1 to ++n, and it will do more than you may imagine!!

Also on today's out-of-order processors -despite the case of "stone-age" compiler- runtime may not be affected at all in many cases!!

Related