Please take a look at this post: Is there a performance difference between i++ and ++i in C?
There are two essential statements in the answer:
- Modern compiler produce the same machine code no matter whether
i++
or++i
is used. - On old compilers
i++
might be slower because it has to remember the old value.
I personally verified statement 1 and can confirm it.
But I have a problem with statement 2 as I cannot find any example where the old value of i
is used and i++
can be replaced by ++i
. To make it clear here is an example:
printf("the value of i is %i\n", i++);
I cannot simply replace i++
with ++i
as it has a different return value. I can only imagine examples where the return value is not used. For example:
while (i < 10)
{
i++;
}
I now can replace i++
with ++i
. But does this make it faster? Did any compiler ever save the old value of a variable which is then never used (the old value)?
Can anyone provide a code example and the disassembly of the compilation where indeed using ++i
instead of i++
makes it faster? Using an old compiler of course.
I hope you understand this is a historical retro question as probably all compilers optimize this for decades.
move.b (a0)+,d0
. With pre-incrementation it has to add 1 to address register first. This is verified by Amiga SAS/C++i
andi++
are supposed to do different things!! Perhaps you meant to say that modern compilers produce the same code for an entire statement consisting of nothing but the expression++i
ori++
.++i
vsi++
, with an extra redundantmov
fori++
to "remember the old value". Try on godbolt. Granted, TCC is what you might call an "aggressively non-optimizing" compiler, but it does show that it's something a primitive compiler might plausibly do.