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

前端 未结 10 1021
[愿得一人]
[愿得一人] 2021-01-30 22:05

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

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

Our instructor asked

10条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 22:41

    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

提交回复
热议问题