Overview and differences between String, StringBuffer and StringBuilder

Overview

String :

String constant, the length of the string is immutable.

StringBuffer :

String variables (Synchronized, that is, thread-safe). If you want to modify the string content frequently, it is better to use StringBuffer for efficiency reasons. If you want to convert to String type, you can call the toString() method of StringBuffer.

The main operations are append and insert methods:

  • The append method always adds these characters to the end of the buffer;
  • The insert method adds characters at the specified point.

StringBuilder :

String variables (not thread safe). Internally, the StringBuilder object is treated as a variable-length array containing a sequence of characters.

This class provides an API compatible with StringBuffer, but does not guarantee synchronization. This class is designed to be used as a simple replacement of StringBuffer, used when the string buffer is used by a single thread (this situation is very common).


The difference between the three

StringAnd the type StringBufferof difference:

String is an immutable object, so every time the String type is changed, a new String object will be generated, and then the pointer will point to the new String object, so it is best not to use String for strings that frequently change content.

When using the StringBuffer class, every time you operate on the StringBuffer object itself, instead of generating a new object and changing the object reference. Therefore, it is recommended to use StringBuffer in most cases, especially when the string object changes frequently.

StringBuilderAnd StringBufferthe difference between:

StringBuffer is thread-safe, StringBuilder is not thread-safe.

In the same situation, using StringBuilder can only obtain a performance improvement of about 10%~15% compared to using StringBuffer, but at the risk of multi-threading insecurity.

In most cases, StringBuilder> StringBuffer. This is mainly because the former does not need to consider thread safety.


Use strategy

(1) Basic principles: If you want to manipulate a small amount of data, use String; single-threaded manipulate large amounts of data, use StringBuilder; multi-threaded manipulate large amounts of data, use StringBuffer.

(2) Do not use the "+" of the String class for frequent splicing, because the performance is extremely poor, you should use the StringBuffer or StringBuilder class, which is a more important principle in Java optimization.
E.g:

String result = "";
for (String s : hugeArray) {
    
    
    result = result + s;
}

// 使用StringBuilder
StringBuilder sb = new StringBuilder();
for (String s : hugeArray) {
    
    
    sb.append(s);
}
String result = sb.toString();

Guess you like

Origin blog.csdn.net/qq_43229056/article/details/109255598