The difference between String, StringBuffer and StringBuilder——(detailed description)

The difference between String, StringBuffer and StringBuilder:

String StringBuffer StringBuilder
Execution speed worst Secondly Highest
Thread safety Thread safety Thread safety Not thread safe
scenes to be used A few string operations A large number of operations in a multi-threaded environment A large number of operations in a single-threaded environment

String:

For String, the data is stored in the constant pool, because all Strings are saved in constant form by default and are modified by final, so they are thread-safe in the thread pool. Because after each String is created, it will no longer change, but its execution speed is the worst.
When we create a String, it processes this information in the constant pool. If a lot of string concatenation work occurs in the program, the efficiency is very low.
Therefore, it is recommended to use String directly when operating a small amount of strings.

StirngBuffer: (not as efficient as StringBuilder, but much higher than String)

StringBuffer is relatively less efficient than StringBuilder, but it is much higher than String. The reason for low efficiency: StringBuffer takes more into account the multi-thread situation. When performing string operations, it uses the synchronize keyword to synchronize the method.
Therefore StringBuffer is suitable for a large number of operations in a multi-threaded environment.

StringBuilder: (without considering thread safety issues)

Thread safety and thread unsafeness :
When performing multi-thread processing, if multiple threads operate on this object at the same time, unexpected results will occur. For StringBuilder, although the execution efficiency is high, it is not recommended to operate the same StringBuilder object in a multi-threaded environment because it is thread-unsafe.
Therefore, StringBuilder is suitable for a large number of string operations in a single-threaded environment.

Guess you like

Origin blog.csdn.net/Turniper/article/details/111112824