i++ 或 ++i 哪个更有效? [英] What is more efficient, i++ or ++i?
问题描述
完全重复:C++ 中的 i++ 和 ++i 之间是否存在性能差异?
完全重复:循环中的 i++ 和 ++i 之间的区别?
i++ 或 ++i 哪个更有效?
What is more efficient, i++ or ++i?
我只在 Java 和 C/C++ 中使用过它,但我真的要求所有实现它的语言.
I have only used this in Java and C/C++, but I am really asking for all languages that this is implemented in.
在大学时,我有一位教授向我们展示了 ++i 的效率更高,但已经有几年了,我想从 StackOverflow 社区获得意见.
In college I had a professor show us that ++i was more efficient, but it has been a couple of years, and I would like to get input from the Stack Overflow community.
推荐答案
i++ :
- 创建 i 的临时副本
- 增量 i
- 返回临时副本
++i :
- 增量 i
- 返回我
通过优化,结果程序集很可能是相同的,但是 ++i 效率更高.
With optimizations on, it is quite possible that the resulting assembly is identical, however ++i is more efficient.
请记住,在 C++ 中,我可能是支持前缀和后缀 ++ 运算符的任何对象.对于复杂对象,临时复制成本是不可忽略的.
edit : keep in mind that in C++, i may be whatever object that support the prefix and postfix ++ operator. For complex objects, the temporary copy cost is non negligible.
这篇关于i++ 或 ++i 哪个更有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!