Is there a performance difference between i++ and ++i in C?

前端 未结 14 998
遥遥无期
遥遥无期 2020-11-22 10:08

Is there a performance difference between i++ and ++i if the resulting value is not used?

14条回答
  •  Happy的楠姐
    2020-11-22 10:57

    First of all: The difference between i++ and ++i is neglegible in C.


    To the details.

    1. The well known C++ issue: ++i is faster

    In C++, ++i is more efficient iff i is some kind of an object with an overloaded increment operator.

    Why?
    In ++i, the object is first incremented, and can subsequently passed as a const reference to any other function. This is not possible if the expression is foo(i++) because now the increment needs to be done before foo() is called, but the old value needs to be passed to foo(). Consequently, the compiler is forced to make a copy of i before it executes the increment operator on the original. The additional constructor/destructor calls are the bad part.

    As noted above, this does not apply to fundamental types.

    2. The little known fact: i++ may be faster

    If no constructor/destructor needs to be called, which is always the case in C, ++i and i++ should be equally fast, right? No. They are virtually equally fast, but there may be small differences, which most other answerers got the wrong way around.

    How can i++ be faster?
    The point is data dependencies. If the value needs to be loaded from memory, two subsequent operations need to be done with it, incrementing it, and using it. With ++i, the incrementation needs to be done before the value can be used. With i++, the use does not depend on the increment, and the CPU may perform the use operation in parallel to the increment operation. The difference is at most one CPU cycle, so it is really neglegible, but it is there. And it is the other way round then many would expect.

提交回复
热议问题