In this article we are gonna discuss the differences between
StringBuffer. Before discussing the differences, lets have a look at what java documentation says about these classes:
A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.
StringBuilder vs StringBuffer
Lets summarize the differences in detail:
1) Synchronization: StringBuffer methods are synchronized while StringBuilder methods are non-synchronized, it means that for thread-safe operations you must choose StringBuffer class instead of StringBuilder.
2) Performance: In a synchronized environment a single thread can perform a certain operation rather than distributing the work among multiple threads, which makes StringBuffer low performer as it is synchronized. StringBuilder performance is better than StringBuffer because it is not synchronized.
3) Which one to use: Operations (without considering the performance) are almost same in both the classes which means there is nothing in StringBuffer which cannot be done using StringBuilder. As discussed above the main thing which you need to consider while making a choice is thread-safety, if you think that the operation should be thread-safe then use StringBuffer, in all other cases StringBuilder is a better choice as it offers you the same functionality with better performance.
Unlike String, both StringBuffer and StringBuilder are mutable (can be modified).
That’s all I have for this discussion. If you feel that there is something that needs to be added or modified in the above article, you are free to drop a comment below and we will review and update the post as required.