The Java compiler ( javac ) does not perform such an optimization. The JIT compiler will most likely build a length() method, which at least avoids the overhead of invoking the method.
Depending on which JDK you are using, the length() method will most likely return a final field of length , which is cheap memory access or the length of the char[] internal array. In the latter case, the length of the array is constant, and the reference to the array is supposedly final , so the JIT can be complex enough to write the length once in the temporary, as you suggest. However, such a thing is an implementation detail. Unless you control every machine your code runs on, you should not make too many assumptions about which JVM it will run or which optimizations it will perform.
As for how you should write your code, calling length() directly in the loop condition is a general code template and allows you to read. I would keep it simple and let the JIT optimizer do its job if you donβt have critical code that showed performance problems and you also showed that such micro-optimization is worth it.
Mike strobel
source share