本文介绍了Java for循环最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您需要索引时,循环数组的最佳方法是什么?

What is the best way to loop through an array when you need the index?

选项1:

int len = array.length;
for (int i = 0; i < len; ++i) {
    array[i] = foo(i);
}

选项2:

for (int i = 0; i < array.length; i++) {
    array[i] = foo(i);
}

或者,这没关系?或者有更好的方法吗?
只是指出差异:在一种情况下,数组的长度作为循环中测试的一部分进行评估,尽管编译器通常应优化它。



其次, ++ i 这里与 i ++ 有什么不同?我肯定更喜欢 ++ i 如果它是C ++但我不确定Java。

Or, does it not matter? Or is there a better way to do it?Just to point out the differences: In one case, the length of the array is evaluated as part of the test in the loop, although the compiler should normally optimize that.


Secondly, is ++i any different here from i++? I definitely prefer ++i if it is C++ but am not sure for Java.

推荐答案

i ++ vs ++ i 在这种特殊情况下无关紧要。虽然C大师会告诉你将array.length存储在一个变量中,但现代优化编译器在这种情况下只要长度不会在循环中发生变化就不必要了。如果你真的担心你可以对两者进行基准测试,但是因为 .length 实际上并不需要每次你都可以遍历整个数组。

i++ vs ++i does not matter in this particular case. While C masters will tell you to store array.length in a variable, modern optimizing compilers make that unnecessary in this case as long as the length does not change in the loop. If you're really concerned you can benchmark both, but since .length doesn't actually need to traverse the entire array each time you'll be OK.

这篇关于Java for循环最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 03:24