The difference between StringBuilder and StringBuffer
Inheritance structure
It can be seen that the common interface among the three, the implementation methods are mostly the same, but the form is different.
The source code
Take a look at their partial source String
public final class String
implements java.io.Serializable.Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
/** Cache the hash code for the string */
private int hash; // Default to 0
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -6849794470754667710L;
/**
* Class String is special cased within the Serialization Stream Protocol.
*
* A String instance is written into an ObjectOutputStream according to
* <a href="{@docRoot} /.. / platform/serialization/spec/output. The HTML "> * Object serialization Specification, Section 6.2," Stream Elements "< / a > * /
private static final ObjectStreamField[] serialPersistentFields =
new ObjectStreamField[0];
/**
* Initializes a newly created {@code String} object so that it represents
* an empty character sequence. Note that use of this constructor is
* unnecessary since Strings are immutable.
*/
public String(a) {
this.value = "".value; }... }Copy the code
StringBuffer
@Override
public synchronized StringBuffer append(Object obj) {
toStringCache = null;
super.append(String.valueOf(obj));
return this;
}
@Override
public synchronized StringBuffer append(String str) {
toStringCache = null;
super.append(str);
return this;
}
Copy the code
StringBuilder
@Override
public StringBuilder append(Object obj) {
return append(String.valueOf(obj));
}
@Override
public StringBuilder append(String str) {
super.append(str);
return this;
}
Copy the code
AbstractStringBuilder
abstract class AbstractStringBuilder implements Appendable.CharSequence {
/** * The value is used for character storage. */
char[] value;
/** * The count is the number of characters used. */
intcount; . }Copy the code
StringBuffer is an immutable StringBuffer and StringBuiler is a mutable StringBuffer. StringBuiler is unlocked
conclusion
- String, StringBuilder, and StringBuffer all implement the CharSequence interface
- String is immutable, its member variables are private final, and there is no way to modify the variables
- String frequently changes characters, resulting in a large amount of heap memory garbage
- The value of StringBuffer and StringBuiler are mutable types and are suitable for scenarios where strings change frequently
- The StringBuffer method is locked, thread safe, and slows operations
- The StringBuilder method is unlocked, thread unsafe and fast