Let’s analyze the string concatenation below.
1.String
Open the source code of String, as shown in the figure
You will find that the character value that stores the string is a final constant. Looking at the construction method of String, we found that the value of String is determined by the construction method. It is necessary to explain the keyword final here
The attribute modified by final is a constant (the value cannot be changed). It is either assigned a value while declaring it or assigned a value in the construction method. Once assigned, it cannot be changed.
Therefore, using String to implement string stitching. Since the value of String cannot be changed, a new String must be generated for each stitching to store a new string. Therefore, using String to handle string stitching will have very low performance.
For more information about String, please refer to the blog: http://longpo.iteye.com/blog/2199493
2.StringBuffer
The StringBuffer class inherits the abstract class AbstractStringBuilder class and opens the AbstractStringBuilder source code.
Let’s take a look at the three overloading methods
It is found that all the constructors of the parent class AbstractStringBuilder are called.
It was found that the char array in which the StringBuffer stores data is not of final type, which means that it can be changed, and the constructed strings still have free space to splice the strings.
In StringBuffer, we use the append() function to splice strings. We can think that although there is still left in the char array, it is definitely not enough to splice it all the time. Therefore, it is necessary to look at the source code implementation of the append function.
Check out the append method of its parent class AbstractStringBuilder
When the value array is not capable of sufficient capacity, a new value array is created to store the string. At this point, you should understand the principle of StringBuffer string splicing. When the char value array is insufficient, a larger capacity array will be created to store. The efficiency is significantly higher than that of String.
3.StringBuilder
StringBuilder and StringBuffer are two brothers, and their usage is basically the same. The difference is that StringBuffer is synchronized and thread-safe, while StringBuilder does not guarantee synchronization and thread-safe.
StringBuilder is faster than StringBuffer in most implementations, and when string buffers are accessed by a single thread, it is recommended to use StringBuilder first.
The above is the Java string choice introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!