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

The difference between StringBuffer and StringBuilder in Java

高洛峰
高洛峰Original
2017-01-22 11:44:221612browse

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

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!

Statement:
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