C 中的 i++ 和 ++i 之间有性能差异吗? [英] Is there a performance difference between i++ and ++i in C?
问题描述
如果不使用结果值,i++
和 ++i
之间是否存在性能差异?
Is there a performance difference between i++
and ++i
if the resulting value is not used?
推荐答案
执行摘要:No.
i++
可能比 ++i
慢,因为 i
的旧值可能需要保存以备后用,但实际上所有现代编译器会对此进行优化.
i++
could potentially be slower than ++i
, since the old value of i
might need to be saved for later use, but in practice all modern
compilers will optimize this away.
我们可以通过查看这个函数的代码来证明这一点,都带有 ++i
和 i++
.
We can demonstrate this by looking at the code for this function,
both with ++i
and i++
.
$ cat i++.c
extern void g(int i);
void f()
{
int i;
for (i = 0; i < 100; i++)
g(i);
}
文件是一样的,除了++i
和i++
:
The files are the same, except for ++i
and i++
:
$ diff i++.c ++i.c
6c6
< for (i = 0; i < 100; i++)
---
> for (i = 0; i < 100; ++i)
我们将编译它们,并获得生成的汇编器:
We'll compile them, and also get the generated assembler:
$ gcc -c i++.c ++i.c
$ gcc -S i++.c ++i.c
而且我们可以看到生成的对象文件和汇编文件都是一样的.
And we can see that both the generated object and assembler files are the same.
$ md5 i++.s ++i.s
MD5 (i++.s) = 90f620dda862cd0205cd5db1f2c8c06e
MD5 (++i.s) = 90f620dda862cd0205cd5db1f2c8c06e
$ md5 *.o
MD5 (++i.o) = dd3ef1408d3a9e4287facccec53f7d22
MD5 (i++.o) = dd3ef1408d3a9e4287facccec53f7d22
这篇关于C 中的 i++ 和 ++i 之间有性能差异吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!