Home > Java > javaTutorial > body text

What is the difference between stringbuffer and stringbuilder in string?

coldplay.xixi
Release: 2020-07-02 14:14:42
Original
4929 people have browsed it

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.

What is the difference between stringbuffer and stringbuilder in string?

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;
}
Copy after login

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);
}
Copy after login

StringBuilder code snippet:

@Override
public String toString() {
    // Create a copy, don't share the array
    return new String(value, 0, count);
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!