Java for loop assessment

I want to know if the conditional evaluation is performed in the for and while loops in Java at the end of each cycle

Example:

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 is executed at the end of each cycle Length? Assumptions and experience tell me yes I know in this example, tenbig Length is a constant and therefore has no performance impact But we assume that conditional operation takes a long time in different situations I know it's reasonable to put tenbig Length is assigned to the variable

I still want to make sure that every time I evaluate it

Solution

Yes, it will logically evaluate the entire intermediate operand in each iteration of the loop When JIT knows better, of course, it can do some smart things (even remove array boundary checking in the loop according to the loop conditions)

Note that for types unknown to the JIT, it may not be able to perform specific optimizations like this - but it can still inline content such as getting the size () of ArrayList < T >

Finally, I usually prefer the enhanced for loop to improve readability:

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

Of course, suppose you don't need an index for other reasons

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>