Quality Testing

Quality is delighting customers

Diff between StringBuffer and StringBuilder

Views: 126

Reply to This

Replies to This Discussion

Difference between StringBuffer and StringBuilder

StringBuffer is the thread safe utility class to perform several operations on Strings. It contains append() and insert() methods that are widely used to perform operation on Strings in a multi-thread environment. If you will check the source code, most of its functions are synchronized for thread safety.

Since most of the String operations, for example concatenation happens in a single thread environment, Java 1.5 introduced another utility class StringBuilder to perform similar operations but doesn’t provide thread safety. If you will look into its source code, all the methods are unsynchronized. This is the most important point for StringBuffer vs StringBuilder.

StringBuffer has some extra methods such as substring, length, capacity, trimToSize etc. However these are not required since you have all these present in String too. That’s why these methods were never implemented in StringBuilder class.

StringBuffer was introduced in Java 1.0 whereas StringBuilder class was introduced in Java 1.5 after looking at shortcomings of StringBuffer

StringBuilder is faster than StringBuffer because of no synchronization.

StringBuffer Example

public class BufferTest{
public static void main(String[] args){
StringBuffer buffer=new StringBuffer("hello");

StringBuilder Example

public class BuilderTest{
public static void main(String[] args){
StringBuilder builder=new StringBuilder("hello");

Performance Test of StringBuffer and StringBuilder

public class ConcatTest{
public static void main(String[] args){
long startTime = System.currentTimeMillis();
StringBuffer sb = new StringBuffer("Java");
for (int i=0; i<10000; i++){
System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms");
startTime = System.currentTimeMillis();
StringBuilder sb2 = new StringBuilder("Java");
for (int i=0; i<10000; i++){
System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms");


Time taken by StringBuffer: 16ms
Time taken by StringBuilder: 0ms

Source: javapoint.com


TTWT Magazine





© 2020   Created by Quality Testing.   Powered by

Badges  |  Report an Issue  |  Terms of Service