++i 和 i++ 之间的区别在 for 循环中
我很了解后缀和前缀递增/递减的工作原理。但我的问题是,在 for 循环中,哪个更高效或更快,哪个更常用,为什么?
前缀?
for(i = 0; i < 3; ++i) {...}
还是后缀?
for(i = 0; i < 3; i++) {...}
I understand well how postfix and prefix increments/decrements work. But my question is, in a for loop, which is more efficient or faster, and which is more commonly used and why?
Prefix?
for(i = 0; i < 3; ++i) {...}
Or postfix?
for(i = 0; i < 3; i++) {...}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于这种情况下的 int 来说,没有区别——编译器将在大多数优化级别下发出相同的代码(我敢说,即使在没有优化的情况下)。
在其他上下文中,例如 C++ 类实例,存在一些差异。
For
int
s in this context there is no difference -- the compiler will emit the same code under most optimization levels (I'd venture to say even in the case of no optimization).In other contexts, like with C++ class instances, there is some difference.
在这种特殊情况下,实际上没有一个比另一个更有效。我希望 ++i 会更常用,因为这对于其他类型的迭代(例如迭代器对象)来说会更有效。
In this particular case, none is actually more efficient than the other. I would expect
++i
to be more commonly used, because that's what would be more efficient for other kinds of iterations, like iterator objects.在我看来,在 for 循环中选择前缀或后缀取决于语言本身。在 C++ 中,前缀更加高效和一致。因为在前缀类型中,编译器不需要复制未递增的值。除了你的值不能是整数之外,如果你的值是一个对象,那么这个前缀类型就更强大了。
In my opinion, choosing prefix or postfix in a for loop depends on the language itself. In c++ prefix is more efficient and consistent. Because in the prefix type, compiler does not need to copy of unincremented value. Besides your value must not be an integer, if your value is an object than this prefix type is more powerful.
两者都有效,在这种情况下,其中一个并不比另一个更高效或更快。人们通常使用 ++1,也许是因为 K&R 和其他有影响力的书籍中使用了 ++1。
Either works, and one is not more efficient or faster than the other in this case. It's common for people to use ++1, maybe because that is what was used in K&R and other influential books.