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

查看:34
本文介绍了在java的for循环中,++i真的比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真的比i++快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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