What is the main difference between StringBuffer
and StringBuilder
?
Is there any performance issues when deciding on any one of these?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
StringBuilder is not thread safe. String Buffer is. More info here.
EDIT: As for performance , after hotspot kicks in , StringBuilder is the winner. However , for small iterations , the performance difference is negligible.
The major difference is
StringBuffer
is syncronized butStringBuilder
is not.If you need to use more than one thread , then StringBuffer is recommended.But, as per the execution speedStringBuilder
is faster thanStringBuffer
, because its not syncronized .Here are the differences, i have noticed :
StringBuffer :-
StringBuilder:-
Common thing :-
StringBuilder
is faster thanStringBuffer
because it's notsynchronized
.Here's a simple benchmark test:
A test run gives the numbers of
2241 ms
forStringBuffer
vs753 ms
forStringBuilder
.StringBuilder
andStringBuffer
are almost the same. The difference is thatStringBuffer
is synchronized andStringBuilder
is not. Although,StringBuilder
is faster thanStringBuffer
, the difference in performance is very little.StringBuilder
is a SUN's replacement ofStringBuffer
. It just avoids synchronization from all the public methods. Rather than that, their functionality is the same.Example of good usage:
If your text is going to change and is used by multiple threads, then it is better to use
StringBuffer
. If your text is going to change but is used by a single thread, then useStringBuilder
.Every method present in StringBuffer is Synchronized. hence at a time only one thread is allowed to operate StringBuffer object. It Increases waiting time of a Thread and Creates Performance problems to overcome this problem SUN People intoduced StringBuilder in 1.5 version.