Java for Loop evaluation

前端 未结 9 2275
孤独总比滥情好
孤独总比滥情好 2020-12-03 21:45

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

Example:

9条回答
  •  有刺的猬
    2020-12-03 22:22

    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).

    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.

    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.

提交回复
热议问题