Consider the following Java code fragment:
String buffer = "...";
for (int i = 0; i < buffer.length(); i++)
{
System.out.println(buffer.charAt(i));
}
Since String
is immutable and buffer
is not reassigned within the loop, will the Java compiler be smart enough to optimize away the buffer.length()
call in the for loop's condition? For example, would it emit byte code equivalent to the following, where buffer.length()
is assigned to a variable, and that variable is used in the loop condition? I have read that some languages like C# do this type of optimization.
String buffer = "...";
int length = buffer.length();
for (int i = 0; i < length; i++)
{
System.out.println(buffer.charAt(i));
}