Here's an analysis of string concatenation.
1.String
Open the source of the string, as shown in the figure
You will find that the character value of the stored string is the final constant. Looking at the construction method of string, we find that the value of string is determined in the construction method. Here is the need to explain the following keyword final
The final decorated property is a constant (the value is immutable), is either assigned at the same time as the declaration, or is assigned within the constructor, and cannot be changed once assigned.
So, string concatenation is used, and because the value of string is immutable, a new string is generated for each concatenation to store the new strings. So using string to handle string concatenation performance can be very low.
For more information about string, refer to Blog: http://longpo.iteye.com/blog/2199493
2.StringBuffer
The StringBuffer class inherits the abstract class Abstractstringbuilder class, opens the Abstractstringbuilder source code
Let's stringbuffer. Three construction methods for overloading
Discovery is the construction method that calls the parent class Abstractstringbuilder
The char array that discovers the StringBuffer storage data is not final type, which indicates that it can be changed, and the constructed string has a free position to stitch the string.
In StringBuffer we use the Append () function for concatenation of strings. We can imagine that although the char array still has the remaining, but the stitching is certainly not enough. So it is necessary to look at the append function of the source code implementation.
Append method for viewing the abstractstringbuilder of its parent class
It is found that when the value array is not sufficient, a new value array is created to store the string. Here you should understand the principle of stringbuffer string concatenation. When a char value array is not sufficient, a larger-capacity array is created to store it. Efficiency is significantly higher than string.
3.StringBuilder
StringBuilder and StringBuffer are two brothers, the use is basically the same, the difference is that StringBuffer is synchronized, thread-safe, and StringBuilder does not guarantee synchronization, thread is not secure.
StringBuilder is faster than StringBuffer in most implementations, and it is recommended that StringBuilder be used preferentially when a string buffer is accessed by a single thread.