StringBuilder or StringBuffer
String is an immutable data type (does not allow modification data after instantiation) while StringBuilder and StringBuffer are mutable data types.
The table below will list the different characteristics between StringBuffer and StringBuilder.
No. | StringBuffer | StringBuilder |
1. Mechanism | StringBuffer is synchronized (thread-safe). It means two threads can’t execute simultaneously methods of StringBuffer. | StringBuilder is non-synchronized (not thread-safe). It means two threads can execute simultaneously methods of StringBuilder. |
2. Efficient | StringBuffer is less efficient than StringBuilder. | StringBuilder is more efficient than StringBuffer. |
3. Time was born | StringBuffer was introduced in JDK 1.0 | StringBuilder was introduced in JDK 1.5 |
The snippet code below will prove the efficiency of StringBuilder.
Long startTime = System.currentTimeMillis();
StringBuffer testBuffer = new StringBuffer();
for(int i = 0; i < 100000; i++){
testBuffer.append("Test_Text");
}
System.out.println("Length of testBuffer text: " + testBuffer.length());
System.out.println("Time executed StringBuffer: "+ (System.currentTimeMillis() - startTime) + "ms");
System.out.println();
startTime = System.currentTimeMillis();
StringBuilder testBuilder = new StringBuilder();
for(int i = 0; i < 100000; i++){
testBuilder.append("Test_Text");
}
System.out.println("Length of testBuilder text: " + testBuilder.length());
System.out.println("Time executed testBuilder: "+ (System.currentTimeMillis() - startTime) + "ms");
Result:
Length of testBuffer text: 900000
Time executed StringBuffer: 17ms
Length of testBuilder text: 900000
Time executed testBuilder: 3ms
Conclusion:
Depending on the situation we will use StringBuilder or StringBuffer. Under thread-safe circumstances for consistent data, the StringBuffer is preferred over StringBuilder. In other cases, StringBuilder is the preferred use.
Heart up and share if the post is useful. Thank you.
Happy Codding.!!! <3