The difference between String, StringBuilder, StringBuffer

The difference between these three classes is mainly in two aspects, namely, the speed of operation and thread safety.

Running speed

StringBuilder > StringBuffer > String

The reason for the slowest String:

  String is a string constant, and StringBuilder and StringBuffer are both string variables, that is, once the String object is created, the object cannot be changed, but the objects of the latter two are variables and can be changed

Thread safe

StringBuilder is thread-unsafe, while StringBuffer is thread-safe.

If a StringBuffer object is used by multiple threads in the string buffer, many methods in StringBuffer can have the synchronized keyword, so the thread can be guaranteed to be safe, but the StringBuilder method does not have this keyword, so thread safety cannot be guaranteed , There may be some wrong operations. So if the operation to be performed is multi-threaded, then StringBuffer must be used, but in the case of single-threaded, it is recommended to use a faster StringBuilder

to sum up:

       String: suitable for a small number of string operations

  StringBuilder: suitable for a large number of operations in the character buffer under a single thread

  StringBuffer: Applicable to the situation where a large number of operations are performed in the character buffer under multithreading

 

The original blog is reprinted at: https://www.cnblogs.com/su-feng/p/6659064.html

Guess you like

Origin blog.csdn.net/qq_34050399/article/details/111311076