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!