Question

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.

Was it helpful?

Solution

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:

  1. You are in a performance critical piece of code.
  2. Storing the length in the local variable actually does give a speed up.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top