When we should use StringBuilder over String concatenation in Java?

When it affects memory or performance we should consider using StringBuilder over String contamination. If we are concatenating a couple of strings once, no worries.

But if we are going to do it over and over again, we should see a measurable difference when using StringBuilder.

Let’s consider the following code:

String concatenation

// Inefficient usage of immutable String
String str = "User";
int count = 100;
for (int i = 1; i <= count; i++) {
    str += i;
}
System.out.println(str);

The above code will create 99 new String objects. Creating new objects is not efficient.

StringBuilder

// Efficient usage of mutable StringBuffer
StringBuffer str = new StringBuffer(100);
str.append("User");
for (int i = 1; i <= 100; i++) {
   str.append(i);
}
System.out.println(str.toString());

The above code will create only two new objects, the StringBuffer and the final String.