java中`For`循环的最佳实践 [英] Best Practice in `For` loop in java

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

问题描述


可能重复:

for loop optimization

在java中我有一段代码:

In java i have a block of code:

List e = {element1, element2, ...., elementn};
for(int i = 0; i < e.size(); i++){//Do something in here
};

和另一个区块:

List e = {element1, element2, ...., elementn};
int listSize = e.size();
for(int i = 0; i < listSize; i++){//Do something in here
};

我认为第二个块更好,因为在第一个块中,如果 i ++ ,我们必须再次计算 e.size()来比较中的条件循环。是对还是错?
比较上面的两个块,写作的最佳做​​法是什么?为什么?自己解释并自己尝试这个循环

I think that the second block is better, because in the first block, if i++, we have to calculate e.size() one more times to compare the condition in the for loop. Is it right or wrong? And comparing the two block above, what is the best practice for writing for? And why?Explain clearly and try this loop yourself

推荐答案

我个人会改用for语句:

Personally I'd use the enhanced for statement instead:

for (Object element : e) {
    // Use element
}

当然,除非你需要索引。

如果我使用两种形式中的一种,我会使用第一种,因为它更整洁(它不会引入另一种仅在该循环中使用的局部变量),直到我具体有证据表明它造成了问题。 (在大多数列表实现中, e.size()是一个简单的变量访问,无论如何都可以通过JIT内联。)

If I had to use one of the two forms, I'd use the first as it's tidier (it doesn't introduce another local variable which is only used in that loop), until I had concrete evidence that it was causing a problem. (In most list implementations, e.size() is a simple variable access which can be inlined by the JIT anyway.)

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

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