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
Better use StringBuilder since it is not synchronized and therefor better performance. StringBuilder is a drop-in replacement of the older StringBuffer.
StringBuffer:
StringBuilder
StringBuffer
is synchronized, butStringBuilder
is not. As a result,StringBuilder
is faster thanStringBuffer
.Since
StringBuffer
is synchronized, it needs some extra effort, hence based on perforamance, its a bit slow thanStringBuilder
.String is an immutable object which means the value cannot be changed where as StringBuffer is mutable.
The StringBuffer is Synchronized hence thread safe where as StringBuilder is not and suitable for only single threaded instances.
Check the internals of synchronized append method of
StringBuffer
and non-synchronized append method ofStringBuilder
.StringBuffer:
StringBuilder:
Since append is
synchronized
,StringBuffer
has performance overhead compared toStrinbBuilder
in multi-threading scenario. As long as you are not sharing buffer among multiple threads, useStringBuilder
, which is fast due to absence ofsynchronized
in append methods.