I found a section in some code at work where a bunch of long strings were created with this format:
String s = "" +
"...\n" +
"...\n" +
Just out of curiosity decided to do a quick test to see if a StringBuilder would make any noticeable difference.
public class TestStringConcat {
public static void main(String[] args) {
int arraySize = 1000000;
String[] strings1 = new String[arraySize];
String[] strings2 = new String[arraySize];
System.out.println("Testing concat version");
long startTime = System.currentTimeMillis();
for (int i = 0; i < arraySize; i++) {
strings1[i] = "" +
"A big long multiline string"; //35 lines of string omitted
}
long endTime = System.currentTimeMillis();
System.out.println("Time to concat strings: " + (endTime - startTime));
System.out.println("Now testing with stringbuilder ");
startTime = System.currentTimeMillis();
for (int i = 0; i < arraySize; i++) {
StringBuilder sb = new StringBuilder();
sb.append("A big long multiline string"); //35 lines of string omitted
strings2[i] = sb.toString();
}
endTime = System.currentTimeMillis();
System.out.println("Time to build strings with stringbuilder: " + (endTime - startTime));
}
}
The output:
Testing concat version
Time to concat strings: 5
Now testing with stringbuilder
Time to build strings with stringbuilder: 2455
I thought StringBuilders where supposed to be faster, but in this case it's way slower. What's going on?