The difference between stringbuffer and stringbuilder in string is: 1. StringBuffer is thread-safe, while StringBuilder is thread-unsafe; 2. StringBuffer exposes method synchronization, but StringBuilder does not.
The difference between stringbuffer and stringbuilder in string is:
Difference 1: Thread safety
StringBuffer: thread-safe, StringBuilder: thread-unsafe. Because all public methods of StringBuffer are synchronized, and StringBuilder is not StringBuilder modified.
StringBuffer code snippet:
@Override public synchronized StringBuffer append(String str) { toStringCache = null; super.append(str); return this; }
Difference 2: Buffer
StringBuffer code snippet:
private transient char[] toStringCache; @Override public synchronized String toString() { if (toStringCache == null) { toStringCache = Arrays.copyOfRange(value, 0, count); } return new String(toStringCache, true); }
StringBuilder code snippet:
@Override public String toString() { // Create a copy, don't share the array return new String(value, 0, count); }
It can be seen that every time StringBuffer obtains toString, it will directly use the toStringCache value of the buffer area to construct a string.
StringBuilder needs to copy the character array every time and then construct a string.
So, cache flushing is also an optimization of StringBuffer, but the toString method of StringBuffer is still synchronous.
Difference 3: Performance
Since StringBuffer is thread-safe, all its public methods are synchronized, and StringBuilder does not lock and synchronize methods, so There is no doubt that the performance of StringBuilder is much greater than StringBuffer.
Related learning recommendations: Java video tutorial
The above is the detailed content of What is the difference between stringbuffer and stringbuilder in string?. For more information, please follow other related articles on the PHP Chinese website!