In C language, Why does n++
execute faster than n=n+1
?
(int n=...; n++;)
(int n=...; n=n+1;)
Our instructor asked
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
n++
, you will have 2 memory access only (read n, inc n, write n )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