6 ms·
Assuming text is a String variable, the JVM should almost always pull the length call out of the loop anyways, since length() is merely a getter of the final 'c
by bermanoid 15y ago
Assuming text is a String variable, the JVM should almost always pull the length call out of the loop anyways, since length() is merely a getter of the final 'count' field within the also-final String class (see http://www.docjar.com/html/api/java/lang/String.java.html http://www.docjar.com/html/api/java/lang/String.java.html), and hence cannot change within the loop, aside from re-assignment of the text variable itself (which is something that, IIRC, the modern JVMs should notice). In fact, that type of optimization is precisely the reason that if you want to access fields from multiple threads you need to perform some kind of synchronization or mark them volatile, if you don't then the JVM assumes that kind of optimization is allowed, by default, and it will do it in most cases.
That said, if you're really in a performance critical section sometimes it doesn't usually hurt to hand-optimize like this, just in case the optimizer craps out for whatever reason and decides to skip optimizing certain sections of code (these reasons can be hard to predict).