StringBuffer differs from StringBuilder in Java
- 2020-04-01 03:55:03
- OfStack
Earlier in Java, you knew that there was a class called StringBuffer that was used to concatenate long strings. After moving to C#, there is also a class-like function called StringBuilder, short for sb, which is easy to remember.
Later, when I moved back to Java, I found that Java also had StringBuilder, so I wondered why StringBuilder was introduced after StringBuffer.
The original Java StringBuilder (like C#) was non-thread-safe, whereas the earlier StringBuffer had some thread-safe properties. Of course, StringBuilder was introduced primarily because it didn't have to be used in multithreaded situations.
The common use case for StringBuilder (or StringBuffer) is:
public String toString() {
return new StringBuilder()
.append("Name: " + name)
.append("Foo: " + foo)
.append("Bar: " + bar)
.toString();
}
In this case, the StringBuilder is not a class member, it is a local variable, and there is no multithreading problem.
As a result, the StringBuilder was introduced with a very large performance boost and no security issues at all...