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

前端 未结 10 1016
[愿得一人]
[愿得一人] 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:32

    The compiler will optimize n + 1 into nothingness.

    Do you mean n = n + 1?

    If so, they will compile to identical assembly. (Assuming that optimizations are on and that they're statements, not expressions)

    0 讨论(0)
  • 2021-01-30 22:32

    Modern compilers should be able to recognize both forms as equivalent and convert them to the format that works best on your target platform. There is one exception to this rule: variable accesses that have side effects. For example, if n is some memory-mapped hardware register, reading from it and writing to it may do more than just transferring a data value (reading might clear an interrupt, for instance). You would use the volatile keyword to let the compiler know that it needs to be careful about optimizing accesses to n, and in that case the compiler might generate different code from n++ (increment operation) and n = n + 1 (read, add, and store operations). However for normal variables, the compiler should optimize both forms to the same thing.

    0 讨论(0)
  • 2021-01-30 22:35

    Who says it does? Your compiler optimizes it all away, really, making it a moot point.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题