What is the difference between string, stringBuffer and stringBuilder?

What is the difference between string, stringBuffer and stringBuilder?

1. String is immutable, why can't string be changed?

1. The array holding the string is final modified and private, and the string class does not provide/expose a method to modify this string;

2. The string class is modified by final so that it cannot be inherited, thereby preventing subclasses from destroying the immutability of string;

3. The string created by string is stored in the public pool, while the string object created by new is on the heap;

 

2. The difference between StringBuilder and StringBuffer

Both StringBuilder and StringBuffer are inherited from the abstractStringBuider class. In abstractStringBuider, character arrays are also used to store strings, but they are not decorated with final and private keywords. The most important thing is that this abstractStringBuider class also provides many methods for modifying strings, such as the append method. ;

2.1 thread safety

Objects in string are immutable, and can also be understood as constants, thread-safe.

abstractStringBuilder is the public class of stringBuilder and StringBuffer, which defines some basic string operations, such as: append, indexof and other public methods. StringBuffer adds a synchronization lock to the method or a synchronization lock to the method called, so the thread is safe. StringBuilder is introduced by jDK1.5, and does not add synchronization lock to the method, so it is not thread-safe.

2.2 Performance

Every time the String type is changed, a new String object will be generated, and then the pointer will be pointed to the new String object. StringBuffer operates on the StringBuffer object itself every time, instead of generating a new object and changing the object reference. Under the same circumstances, using StringBuilder can only achieve a performance improvement of about 10%-15% compared to using StringBuffer, but there is a risk of multi-threading insecurity.

2.3 Summary of the use of the three

1. Operate a small amount of data: apply String

2. Operate a large amount of data under the single-threaded operation string buffer: apply StringBuilder

3. Multi-threaded operation string buffer to operate a large amount of data: use stringbuffer

Supplement: StringJoiner is a new class in Java8, which is used to construct a character sequence separated by a delimiter, and optionally start from the provided prefix and end with the provided suffix. Its underlying layer is implemented by StringBuilder, so the development Personnel do not need to be spliced ​​through StringBuffer or StingBuilder.

Guess you like

Origin blog.csdn.net/weixin_56602545/article/details/130100429