Home > Java > javaTutorial > The difference between StringBuffer and StringBuilder in Java

The difference between StringBuffer and StringBuilder in Java

高洛峰
Release: 2017-01-22 11:44:22
Original
1581 people have browsed it

When I used Java earlier, I knew that there was a class called StringBuffer, which was used to splice longer strings. After switching to C#, there is also a class with similar functions called StringBuilder. The abbreviation is sb, which is very easy to remember.

Later, when I transferred back to Java, I found that Java also had StringBuilder, so I was curious about why StringBuilder was introduced after StringBuffer.

It turns out that Java's StringBuilder (like C#) is not thread-safe, but the earlier StringBuffer has certain thread-safety attributes. Of course, StringBuilder was introduced mainly because it does not need to be used in multi-threaded situations.

Common StringBuilder (or StringBuffer) use cases are:

public String toString() {
 return new StringBuilder()
  .append("Name: " + name)
  .append("Foo: " + foo)
  .append("Bar: " + bar)
  .toString();
}
Copy after login

In this case, StringBuilder is not a class member, it is just a local variable, not at all Not to mention the issue of multi-threading.

As a result, the introduction of StringBuilder has brought about a huge performance improvement, and there are no security issues at all...

For more articles related to the difference between StringBuffer and StringBuilder in Java, please pay attention to the PHP Chinese website!

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