Difference between StringBuffer and StringBuilder in Java
This post will discuss the difference between StringBuffer and StringBuilder classes in Java.
Strings in Java are immutable, which means that they cannot be modified once they are created. Whenever a change to a String is made, an entirely new String is created. This can cause performance issues and memory waste, especially when we need to concatenate or append multiple Strings.
To overcome this problem, Java provides two alternative classes that can create mutable sequences of characters: StringBuffer and StringBuilder. These classes are similar to String, but they allow us to add, update, delete, or check characters in the sequence without creating a new object.
1. Difference between StringBuffer and StringBuilder
The functionality of StringBuffer and StringBuilder are very similar. They both represent a mutable sequence of characters that can be manipulated and accessed using various methods. However, they also have some significant differences and trade-offs that make them suitable for different use cases:
StringBufferis synchronized,StringBuilderis not. This means thatStringBufferis thread-safe and can be used in multi-threaded environments, whileStringBuilderis not thread-safe and should be used in single-threaded environments. Synchronization ensures data integrity and consistency, but it also adds overhead and reduces performance.StringBufferis slower,StringBuilderis faster. This means thatStringBufferhas lower performance thanStringBuilderunder most circumstances, as it has to handle synchronization and locking mechanisms. On the contrary, none of the methods ofStringBuilderare synchronized. This reduces the overhead of locking and unlocking mechanisms and improves the execution speed.
2. Performance comparison between StringBuffer and StringBuilder
StringBuilder class is recommended over StringBuffer. This is because StringBuilder is faster than StringBuffer since it is not synchronized. To illustrate, consider the following performance benchmark test, which tracks the time taken by StringBuffer and StringBuilder objects on numerous calls to the append() operation.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
class Main { private static final char ch = 'A'; public static StringBuffer stringBufferConcatenation() { StringBuffer s = new StringBuffer(ch); for (int i = 0; i < Short.MAX_VALUE; i++) { s = s.append(ch); } return s; } public static StringBuilder stringBuilderConcatenation() { StringBuilder sb = new StringBuilder(ch); for (int i = 0; i < Short.MAX_VALUE; i++) { sb.append(ch); } return sb; } public static void main(String[] args) { long start = System.nanoTime(); stringBufferConcatenation(); System.out.println("StringBuffer took " + (System.nanoTime() - start) + "ns"); start = System.nanoTime(); stringBuilderConcatenation(); System.out.println("StringBuilder took " + (System.nanoTime() - start) + "ns"); } } |
Output (will vary):
StringBuffer took 2236400ns
StringBuilder took 1245000ns
As evident from the above benchmark test, the time taken by the StringBuffer class is almost twice as compared to the time taken by the StringBuilder class. The StringBuffer class provides the thread-safety, but it comes at a performance cost.
3. What to use and when?
As we have seen, StringBuffer and StringBuilder are both useful classes to create mutable sequences of characters in Java. Here are some general recommendations on choosing between them:
- If you are in a single-threaded environment or can guarantee that the instance will not be accessed by multiple threads,
StringBuilderis the optimal choice for performance.StringBuilderis faster and simpler thanStringBufferand can handle most scenarios where a mutable sequence of characters is needed. - If you are in a multi-threaded environment or cannot guarantee that the instance will not be accessed by multiple threads,
StringBufferis the optimal choice for safety.StringBufferis synchronized and thread-safe and can prevent data inconsistency or concurrency issues.
That’s all about difference between StringBuffer and StringBuilder classes in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)