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
StringBuffer
StringBuilder
StringBuilder
without any other changeString
is an immutable.StringBuffer
is a mutable and synchronized.StringBuilder
is also mutable but its not synchronized.String-Builder :
String-Buffer
It is recommended to use StringBuilder whenever possible because it is faster than StringBuffer. However, if the thread safety is necessary, the best option is StringBuffer objects.
The javadoc explains the difference:
StringBuilder is much faster than StringBuffer because It's non synchronized.
Here you got more idea about the cost of synchronize
Let take programmatically look how much StringBuilder faster than StringBuffer
OutPut
Time taken by StringBuffer: 16ms
Time taken by StringBuilder: 0ms
In single threads, StringBuffer is not significantly slower than StringBuilder, thanks to JVM optimisations. And in multithreading, you can't use safely a StringBuilder.
Here is my test :
Results :
strings: 319740
Buffers : 23
Builder : 7 !
So Builders are faster than Buffers, and WAY faster than strings concatenation. Now let's use an Executor for multiple threads :
Now StringBuffers take 157 ms for 100000 appends. It's not the same test, but compared to the previous 37 ms, you can safely assume that StringBuffers appends are slower with multithreading use. The reason is that the JIT/hotspot/compiler/something makes optimizations when it detects that there is no need for checking locks.
But with StringBuilder, you have java.lang.ArrayIndexOutOfBoundsException, because a concurrent thread tries to add something where it should not.
Conclusion is that you don't have to chase StringBuffers. And where you have threads, think about what they are doing, before trying to gain a few nanoseconds.