Strings are very frequently used in Java programs. This blog post tries to explain what a programmer needs to consider from a performance point of view. It will also explain in what situations you should use StringBuilder instead of String.
Strings in Java are immutable. If you look at the source code of String you find that java.lang.String has the following properties.
/** The value is used for character storage. */ private final char value; /** The offset is the first index of the storage that is used. */ private final int offset; /** The count is the number of characters in the String. */ private final int count;
The array is used to store the values of this String.
As Strings are immutable they can be freely shared. This property is utilized in the method substring(). The method substring will use a reference to the same String and only change the offset and the lenght value for the String. The same string is in this case used several times.
Therefore using substring requires only a constant amount of time (and almost no additional memory) and can be freely used.
The operation concat() (which is called by the + operator) combines two Strings. This method has to copy the characters of the two Strings and therefore takes time and extra space which is propotional to the length of the two strings .
The object StringBuilder has a more effectly way of concatenate Strings. It works similar to the class ArrayList by allocating a predefined array for storing the characters and keeps track of the used space. Every time the space is exceeded then it will extend the available capacity).
Does this means that you always have to use StringBuilder if you are concatening strings?
No. Of course if in your program you combine only a few times String the runtime overhead is normally not relevant for the overall performance.
But of course if you combine frequently strings in your program you should switch to StringBuilder.