No worries about contatenating String in a loop if the buffer does not grow.
import org.junit.Test;
// java 8
public class StringConcatLoopTest {
@Test
public void very_long_when_concat_increasing_size_string() {
String buffer = "";
long start = System.currentTimeMillis();
for (int i = 0; i < 1000 * 50; i++) {
buffer += i + "\n";
}
long stop = System.currentTimeMillis();
System.out.println(stop - start); // 6921
System.out.println(buffer.length()); // 288890
}
@Test
public void quick_when_appending_increasing_size_string() {
StringBuffer buffer = new StringBuffer();
long start = System.currentTimeMillis();
for (int i = 0; i < 1000 * 50; i++) {
buffer.append(i + "\n");
}
long stop = System.currentTimeMillis();
System.out.println(stop - start); // 68
System.out.println(buffer.length()); // 288890
}
@Test
public void quick_when_concat_constant_size_string() {
String buffer = "";
long start = System.currentTimeMillis();
for (int i = 0; i < 1000 * 50; i++) {
buffer = "x" + i + "\n";
}
long stop = System.currentTimeMillis();
System.out.println(stop - start); // 45
System.out.println(buffer.length()); // 7
}
}