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

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

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

14条回答
  •  无人及你
    2020-11-22 10:43

    Short answer:

    There is never any difference between i++ and ++i in terms of speed. A good compiler should not generate different code in the two cases.

    Long answer:

    What every other answer fails to mention is that the difference between ++i versus i++ only makes sense within the expression it is found.

    In the case of for(i=0; i, the i++ is alone in its own expression: there is a sequence point before the i++ and there is one after it. Thus the only machine code generated is "increase i by 1" and it is well-defined how this is sequenced in relation to the rest of the program. So if you would change it to prefix ++, it wouldn't matter in the slightest, you would still just get the machine code "increase i by 1".

    The differences between ++i and i++ only matters in expressions such as array[i++] = x; versus array[++i] = x;. Some may argue and say that the postfix will be slower in such operations because the register where i resides have to be reloaded later. But then note that the compiler is free to order your instructions in any way it pleases, as long as it doesn't "break the behavior of the abstract machine" as the C standard calls it.

    So while you may assume that array[i++] = x; gets translated to machine code as:

    • Store value of i in register A.
    • Store address of array in register B.
    • Add A and B, store results in A.
    • At this new address represented by A, store the value of x.
    • Store value of i in register A // inefficient because extra instruction here, we already did this once.
    • Increment register A.
    • Store register A in i.

    the compiler might as well produce the code more efficiently, such as:

    • Store value of i in register A.
    • Store address of array in register B.
    • Add A and B, store results in B.
    • Increment register A.
    • Store register A in i.
    • ... // rest of the code.

    Just because you as a C programmer is trained to think that the postfix ++ happens at the end, the machine code doesn't have to be ordered in that way.

    So there is no difference between prefix and postfix ++ in C. Now what you as a C programmer should be vary of, is people who inconsistently use prefix in some cases and postfix in other cases, without any rationale why. This suggests that they are uncertain about how C works or that they have incorrect knowledge of the language. This is always a bad sign, it does in turn suggest that they are making other questionable decisions in their program, based on superstition or "religious dogmas".

    "Prefix ++ is always faster" is indeed one such false dogma that is common among would-be C programmers.

提交回复
热议问题