StringBuilder aims to reduce the overhead associated with creating strings.
As you may or may not know, strings are immutable. What this means that something like
String a = "foo";
String b = "bar";
String c = a + b;
String d = c + c;
creates a new string for each line. If all we are concerned about is the final string d
, the line with string c
is wasting space because it creates a new String
object when we don't need it.
String builder simply delays actually building the String
object until you call .toString()
. At that point, it converts an internal char[]
to an actual string.
Let's take another example.
String foo() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; i++)
sb.append(i);
return sb.toString();
}
Here, we only create one string. StringBuilder
will keep track of the chars you have added to your string in its internal char[] value
. Note that value.length
will generally be larger than the total chars you have added to your StringBuilder
, but value
might run out of room for what you're appending if the string you are building gets too big. When that happens, it'll resize, which just means replacing value
with a larger char[]
, and copying over the old values to the new array, along with the chars of whatever you appended.
Finally, when you call sb.toString()
, the StringBuilder
will call a String
constructor that takes an argument of a char[]
.
That means only one String
object was created, and we only needed enough memory for our char[]
and to resize it.
Compare with the following:
String foo() {
String toReturn = "";
for (int i = 0; i < 100; i++)
toReturn += "" + i;
toReturn;
}
Here, we have 101 string objects created (maybe more, I'm unsure). We only needed one though! This means that at every call, we're disposing the original string toReturn
represented, and creating another string.
With a large string, especially, this is very expensive, because at every call you need to first acquire as much memory as the new string needs, and dispose of as much memory as the old string had. It's not a big deal when things are kept short, but when you're working with entire files this can easily become a problem.
In a nutshell: if you're working appending / removing information before finalizing an output: use a StringBuilder
. If your strings are very short, I think it is OK to just concatenate normally for convenience, but this is up to you to define what "short" is.