Java for 循环评估 [英] Java for Loop evaluation

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

问题描述

我想知道Java中的forwhile循环是否在每次循环结束时执行条件评估.

I want to know if the condition evaluation is executed in for and while loops in Java every time the loop cycle finishes.

示例:

int[] tenBig = new int[]{1,2,3,4,5,6,7,8,9,10};

for(int index = 0;index < tenBig.length;index++){
    System.out.println("Value at index: "+tenBig[index]);
}

index <每次循环结束时执行tenBig.length?

假设和经验告诉我是的.

Assumption and experience tells me yes.

我知道在这个例子中 tenBig.length 是一个常数,所以不会有性能影响.

I know that in this example the tenBig.length is a constant, so there won't be a performance impact.

但是让我们假设条件操作在不同的情况下需要很长时间.我知道接下来要做的合乎逻辑的事情是将 tenBig.length 分配给一个变量.

But lets assume that the condition operation takes long in a different case. I know the logical thing to do then is to assign the tenBig.length to a variable.

我仍然想确保它每次都被评估.

Still I want to be sure that its evaluated every time.

推荐答案

是的,它将在循环的每次迭代中逻辑地评估整个中间操作数.当然,在 JIT 知道得更好的情况下,它可以做一些聪明的事情(甚至可能根据循环条件删除循环内的数组边界检查).

Yes, it will logically evaluate the whole of the middle operand on every iteration of the loop. In cases where the JIT knows better, of course, it can do clever things (even potentially removing the array bounds check within the loop, based on the loop conditions).

请注意,对于 JIT 不知道的类型,它可能无法像这样专门优化 - 但仍然可以内联诸如获取 size() 之类的东西ArrayList.

Note that for types that the JIT doesn't know about, it may not be able to optimize specifically like this - but may still inline things like fetching the size() of an ArrayList<T>.

最后,我通常更喜欢增强的 for 循环以提高可读性:

Finally, I generally prefer the enhanced for loop for readability:

for (int value : tenBig) {
    ...
}

当然,这是假设您出于其他原因不需要索引.

Of course, that's assuming you don't need the index for other reasons.

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

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