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

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

问题描述

我想知道是否在每次循环周期结束时在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会在每次循环周期结束时执行吗?

Will the index < tenBig.length be execute every time the loop cycle finishes?

假设和经验告诉我是

我知道在此示例中,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未知的类型,它可能无法像这样专门进行优化-但仍可能内联诸如获取ArrayList<T>size()之类的东西.

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 Loop评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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