The difference between StringBuffer and StringBuilder and String in Java

There are three commonly used classes for processing strings in Java:
1. java.lang.String
2. java.lang.StringBuffer
3. java.lang.StrungBuilder

  • StringBuffer is thread-safe and can be used in multiple threads without additional synchronization;

  • StringBuilder is asynchronous, running in multiple threads requires separate synchronization processing, but the speed is much faster than StringBuffer;

  • StringBuffer and StringBuilder have in common: string operations can be performed through append and indert.

  • String implements three interfaces: Serializable, Comparable, CarSequence

  • StringBuilder only implements two interfaces Serializable and CharSequence. In contrast, String instances can be compared through the compareTo method, while the other two cannot.

Three types of similarities:

They are all final classes and are not allowed to be inherited, mainly for performance and security considerations, because these classes are often used, and to prevent the parameters from being modified to affect other applications.

Three types of differences:

  1. The running and execution speed , in this respect, the running speed is : StringBuilder> StringBuffer> String.

  • String is the slowest reason: 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.
  • The objects of StringBuilder and StringBuffer are variables. To manipulate variables is to directly change the object without creating and recycling operations, so the speed is much faster than String
  1. Thread safety, in terms of thread safety, 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 carry the synchronized keyword, so the thread is safe.
  • But the StringBuilder method does not have this keyword, so thread safety cannot be guaranteed, and some wrong operations may occur. Therefore, if the operation to be performed is multi-threaded, StringBuffer must be used, but in the case of single-threaded, it is recommended to use a faster StringBuilder.

(When a thread accesses the synchronized (this) synchronization code block in an object, other threads trying to access the object will be blocked)

  1. 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: suitable for a large number of operations in the character buffer under multithreading

Transfer from: https://home.cnblogs.com/u/weibanggang/

Guess you like

Origin blog.csdn.net/SwaeLeeUknow/article/details/108978884