String, StringBuffer, StringBuilder difference

String, StringBuffer, StringBuilder difference

String, StringBuffer, StringBuilder are three classes in Java for processing strings

String

Is an immutable class, that is, it cannot be modified after creation. Whenever an operation is performed on a variable of type String, a new String object is created, which leads to inefficient memory usage. Therefore, using the String class can cause performance problems if frequent modification operations are required on the string.

The String class internally saves this final modified value array

private final char value[];

StringBuffer

Is a thread-safe mutable class suitable for sharing among multiple threads. Whenever a variable of StringBuffer type is operated, a new String object will not be created, but will be modified on the basis of the original object.

AbstractStringBuilderThe value array of its parent class is not final type

char[] value;

The methods of this class are all added synchronizedto ensure thread safety

StringBuilder

It is a variable class, similar to StringBuffer, but StringBuilder does not guarantee thread safety. Therefore, when multi-threaded access does not need to be considered, it is recommended to use StringBuilder instead of StringBuffer, because the performance of StringBuilder is higher than that of StringBuffer.

Summarize

If you need to modify the string frequently and only a single thread accesses the object, you should use StringBuilder; if you need to modify the string frequently and multiple threads may access the object, you should use StringBuffer. And if you don't need to modify the string, then you should use String.

Guess you like

Origin blog.csdn.net/m0_52440465/article/details/130417363