Do you understand how it works internally?
Every time you do stringA += stringB;
a new string is created an assigned to stringA, so it will consume memory (a new string instance!) and time (copy the old string + new characters of the other string).
StringBuilder
will use an array of characters internally and when you use the .append()
method it will do several things:
- check if there are any free space for the string to append
- again some internal checks and run a
System.arraycopy
to copy the characters of the string in the array.
Personally, I think the allocation of a new string every time (creating a new instance of string, put the string, etc.) could be very expensive in terms of memory and speed (in while/for, etc. especially).
In your example, use a StringBuilder
is better, but if you need (example) something simple like a .toString()
,
public String toString() {
return StringA + " - " + StringB;
}
makes no differences (well, in this case it is better you avoid StringBuilder overhead which is useless here).