Java for Loop evaluation -
i want know if condition evaluation executed in for
, while
loops in java every time loop cycle finishes.
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 @ index: "+tenbig[index]); }
will index < tenbig.length
execute every time loop cycle finishes?
assumption , experience tells me yes.
i know in example tenbig.length
constant, there won't performance impact.
but lets assume condition operation takes long in different case. know logical thing assign tenbig.length
variable.
still want sure evaluated every time.
yes, logically evaluate whole of middle operand on every iteration of loop. in cases jit knows better, of course, can clever things (even potentially removing array bounds check within loop, based on loop conditions).
note types jit doesn't know about, may not able optimize - may still inline things fetching size()
of arraylist<t>
.
finally, prefer enhanced loop readability:
for (int value : tenbig) { ... }
of course, that's assuming don't need index other reasons.
Comments
Post a Comment