在Java中的for循环中,++我真的比i ++快吗? [英] Is ++i really faster than i++ in for-loops in java?

查看:179
本文介绍了在Java中的for循环中,++我真的比i ++快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中,我通常会生成如下的for循环:

In java I usually make a for-loop like following:

for (int i = 0; i < max; i++) {
   something
}

但是最近一位同事输了它:

But recently a colleague typed it so:

for (int i = 0; i < max; ++i) {
   something
}

他说后者会更快。这是真的吗?

He said the latter would be faster. Is that true?

推荐答案

不,这不是真的。您可以通过对每个循环进行大量迭代计时来衡量性能,但我相当肯定它们是相同的。

No, it's not true. You could measure the performance by timing each loop for a large number of iterations, but I'm fairly certain they will be the same.

神话来自C其中 ++ i 被认为比 i ++ 更快,因为前者可以通过增加i然后返回它来实现。后者可以通过将i的值复制到临时变量,递增i,然后返回临时变量来实现。第一个版本不需要制作临时副本,因此很多人都认为它更快。但是,如果表达式用作语句,现代C编译器可以优化临时副本,以便在实践中没有区别。

The myth came from C where ++i was regarded as faster than i++ because the former can be implemented by incremeting i then returning it. The latter might be implemented by copying the value of i to a temporary variable, incrementing i, then returning the temporary. The first version doesn't need to make the temporary copy and so many people assume that it is faster. However if the expression is used as a statement modern C compilers can optimize the temporary copy away so that there will be no difference in practice.

这篇关于在Java中的for循环中,++我真的比i ++快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆