Differences
Figure 1 String
The following are the differences.
No
|
StringBuffer |
StringBuilder |
1 |
StringBuffer class is synchronized |
StringBuilder class is not synchronized |
2 |
It is thread-safe |
It is not thread-safe |
3 |
It is slower than StringBuilder |
It is faster than StringBuffer |
4 |
It is available from Java 1.0 |
It is available from Java 5.0 |
Explanation of the preceding differences
Synchronization, thread safety & speed
- StringBuffer is synchronized, that's why it is also thread-safe. In other words, two or more threads cannot call the methods of StringBuffer simultaneously.
In a synchronized environment, a single thread can perform a certain operation rather than disturbing any other thread that makes StringBuffer slower because it is synchronized.
- StringBuilder is not synchronized and that's why it is not thread-safe. That means that two or more threads can call the methods of StringBuilder simultaneously. Since it is non-synchronized and not thread-safe, it can perform faster because there is no overhead of acquiring and releasing of locks associated with synchronized methods (StringBuffer).
Note: The only similarity between the two is that they both are mutable.
Preference
All the operations (excluding performance) are nearly similar in both classes. When we need to choose on the basis of thread safety and you want that operation should be thread-safe, then StringBuffer is a good option. Otherwise in all other cases, StringBuilder will be the best option since it gives better performance with all the functionality.
StringBuffer & StringBuilder performance test
Example
- public class PerformanceTest
- {
- public static void main(String[] args)
- {
- long startTime = System.currentTimeMillis();
- StringBuffer strbuff = new StringBuffer("Dark");
- for (int i = 0; i < 10000; i++)
- {
- strbuff.append("Night");
- }
- System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");
- startTime = System.currentTimeMillis();
- StringBuilder strbuild = new StringBuilder("Dark");
- for (int i = 0; i < 10000; i++) {
- strbuild.append("Night");
- }
- System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");
- }
- }
OutputFigure 2 Output Performance Test
You can see that, StringBuilder is faster than StringBuffer since it is performed in 0ms whereas StringBuffer is performed in 15ms.
Conclusion
Parameters |
String |
StringBuffer |
StringBuilder |
Modifiable |
No(immutable) |
Yes(mutable) |
Yes(mutable) |
Thread-safety |
Yes |
Yes |
No |
Storage area |
Constant string pool |
Heap |
Heap |
Synchronization |
Yes |
Yes |
No |
Performance |
Slow |
Fast |
Very fast |
Availability |
Always |
1.0 |
5.0 |
Overrides equals() and hashCode() method |
Yes |
No |
No |
Thank you, keep learning and sharing.