Please go to DobbyKim’s Question of the Day for more questions
A:
An array of characters decorated with the final keyword in the String class holds strings
private final char value[];
Copy the code
So strings are immutable, which results in a new String being created every time a String is added, changed, or deleted. Not only is it inefficient, but it wastes space.
Both StringBuilder and StringBuffer objects are mutable, and both inherit AbstractStringBuilder classes; Any operation on the string they point to does not produce a new object; The difference between them is that StringBuilder is thread-unsafe; Stringbuffers are thread-safe.
The source code shows that StringBuffer is thread-safe. Take a look at the append methods of two classes:
Append method for StringBuffer:
@Override
public synchronized StringBuffer append(String str) {
super.append(str);
return this;
}
Copy the code
StringBuilder append method:
@Override
public StringBuilder append(String str) {
super.append(str);
return this;
}
Copy the code
We can see that both StringBuffer and StringBuilder call the append method of their parent class directly; The difference is that StringBuffer has the synchronized keyword to lock the Append method, so it is thread-safe to use, but it also means that StringBuffer performance is slightly lower than That of StringBuilder.
Usage scenarios of the three:
- You can use String when manipulating small amounts of data
- StringBuilder is useful when a single thread manipulates a large amount of data in a string buffer
- StringBuffer is used when multiple threads manipulate large amounts of data in a StringBuffer