In Java code, I think this:
for (int i = 0; i < s.length(); i++) {
// do a lot of something
}
Is slower than this:
int length = s.length();
for (int i = 0; i < length; i++) {
// do a lot of something
}
Please tell me whether I’m correct.
In theory the first code sample could be slower because it calls
s.length()once per iteration. But it’s possible that the JVM will optimize the first piece of code for you. Use the simpler approach unless benchmarks show that: