StringBuilder is so much faster than string concatenation

I was googling around whether I should use StringBuilder or just regular string concatenation (s += "lol") in Java. So I found out that StringBuilder is supposed to be faster and decided to try it out. Here is the suberp code I ran to figure this out:

long builderStart = System.currentTimeMillis();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 999999; i++) {
long builderEnd = System.currentTimeMillis();

long concatenationStart = System.currentTimeMillis();
String str = "";
for (int i = 0; i < 999999; i++) {
    str += i + "asdf" + "\n";
long concatenationEnd = System.currentTimeMillis();

System.out.println("StringBuilder time: " + (builderEnd - builderStart) + " ms");
System.out.println("String concatenation time: " + (concatenationEnd - concatenationStart) + " ms");

It goes through a for loop almost a million times, each time appending the string slightly. The StringBuilder was faster indeed but I 🤯 just how much faster it was:

StringBuilder time: 57 ms
String concatenation time: 673930 ms

And just to clarify, converting StringBuilder into actual String takes almost no time at all. Here are the results of the same loop + converting it to an actual string:

StringBuilder time: 60 ms
StringBuilder to String time: 16 ms

TLDR: Use StringBuilder if you're handling super long strings or something 🪂


- 6 toasts