Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the differences between StringBuffer and StringBuilder in Java

Shulou Source: shulou.com Published: 2022-06-03 16:18:32 11月14日 Update

This article mainly talks about "what are the differences between StringBuffer and StringBuilder in Java". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "what are the differences between StringBuffer and StringBuilder in Java?"

Let's first look at the class structure of StringBuffer and StringBuilder:

In fact, it is very simple to inherit an abstract string parent class: AbstractStringBuilder. Let's take a look at their three differences.

Difference 1: thread safety

StringBuffer: thread safe, StringBuilder: thread unsafe. Because all exposed methods of StringBuffer are synchronized-decorated, while StringBuilder is not StringBuilder-decorated.

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);}

As you can see, every time StringBuffer fetches toString, it directly uses the toStringCache value of the cache to construct a string.

StringBuilder, on the other hand, needs to copy the character array and construct a string each time.

So, cache flushing is also an optimization of StringBuffer, but the toString method of StringBuffer is still synchronous.

Difference 3: performanc

Since StringBuffer is thread-safe, all its exposed methods are synchronized, and StringBuilder does not synchronize methods, there is no doubt that StringBuilder performs much better than StringBuffer.

Summary

Therefore, StringBuffer is suitable for scenarios where multithreading is used to operate the same StringBuffer, and StringBuilder is more suitable for single-thread scenarios.

At this point, I believe you have a deeper understanding of "what is the difference between StringBuffer and StringBuilder in Java". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Threads methods security characters code strings fragments synchronization content performance learning practicality deeper three interests situations scenarios practicality practicality Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Shulou Information Huawei NVidia vpn