Calling .length() in the for declaration is slower than doing so before the loop?
-
20-06-2021 - |
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.
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:
- You are in a performance critical piece of code.
- Storing the length in the local variable actually does give a speed up.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow