I came across the following code:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100000; i++) {
String line = "foo" + Integer.toString(i) + "bar\n";
sb.append(line);
}
System.out.print(sb.toString());
My question is what the performance/memory differences would be to use the following code instead:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100000; i++) {
sb.append("foo").append(Integer.toString(i)).append("bar\n");
}
System.out.print(sb.toString());
or
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100000; i++) {
sb.append(String.format("foo %i bar", i\n));
}
System.out.print(sb.toString());
I saw a lot of questions/answers showing that using: String cumulativeOutput = ""; ... cumulativeOutput += "foo" + Integer.toString(i) + "bar\n";
is wasteful (essentially creating a new StringBuilder on every loop iteration), but didn't see any direct answers regarding the above situation. I have also seen that the length of the strings matters, and would be interested in seeing how the following code would compare:
StringBuilder sb = new StringBuilder();
String foo = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ";
String bar = " Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n";
for (int i = 1000000000; i < 1000100000; i++) {
String line = foo + Integer.toString(i) + bar;
sb.append(line);
}
System.out.print(sb.toString());
I expect the second loop will be fastest (chaining .append), but am interested if there's some hidden details. Looking forward to see what others find or know!