@Mcoder said:@pkmnfrk said:Doesn't javac convert string concatenations like that into a StringBuffer anyway? I recall reading something like that last time I cared about java. Yes, it does.It didn't by the turn of the century, but was fixed by then. The entire thing is a nest of WTFs, but after a couple of decades Sun made it act at the way you expect (just don't look inside). I was left wondering at what year that co-worker thinks he's living. The thing is this: The code
for(int i=0; i < someLimit; i++) {
...
stringVar = stringVar + some_other_string;
...
}
is compiled into
for(int i=0; i < someLimit; i++) {
...
StringBuilder temp = new StringBuilder();
temp.append(stringVar);
temp.append(some_other_string);
stringVar = temp.toString();
...
}
which is fine in its own, but since it is inside a loop, it can be tuned a lot like this, avoiding unneccessary creation of StringBuilder objects and toString() method calls:
StringBuilder temp = new StringBuilder();
for(int i=0; i < someLimit; i++) {
...
temp.append(some_other_string);
...
}
stringVar = temp.toString();