StringBuffer Vs StringBuilder in Java

StringBuffer Vs StringBuilder:

StringBuffer: 

  • StringBuffer is mutable, means instance of an object can be modified without creating new object.
  • StringBuffer is synchronized.
  • StringBuffer is thread safe.
  • StringBuffer is slow than StringBuilder.

StringBuilder:

  • StringBuilder is also mutable, means in StringBuilder also instance of an object can be modified without creating new object.
  • StringBuilder is not synchronized
  • StringBuilder is not thread safe.
  • StringBuilder is faster than StringBuffer, since it is not synchronized and not thread safe.

StringBuilder is faster than StringBuffer, you can understand this term by the below program,

[java]
public class StringBufferVsStringBuilder{
public static void main(String[] args){
long startTimeStringBuffer = 0;
long startTimeStringBuilder = 0;
long endTimeStringBuffer = 0;
long endTimeStringBuilder = 0;
int value = 93483493;
int stringBuff = 0;
int stringBuil = 0;
{
StringBuffer sBuffer = new StringBuffer();
startTimeStringBuffer = System.currentTimeMillis();
while(stringBuff< value){
sBuffer.append("");
stringBuff++;
}
endTimeStringBuffer = System.currentTimeMillis();
System.out.println("Total Time taken by StringBuffer is :"+(endTimeStringBuffer-startTimeStringBuffer));
}
{
StringBuilder sBuilder = new StringBuilder();
startTimeStringBuilder = System.currentTimeMillis();
while(stringBuil< value){
sBuilder.append("");
stringBuil++;
}
endTimeStringBuilder = System.currentTimeMillis();
System.out.println("Total Time taken by StringBuilder is :"+ (endTimeStringBuilder-startTimeStringBuilder));
}

}
}
[/java]

Output:
Total Time taken by StringBuffer is :2300
Total Time taken by StringBuilder is :1051

 

 

 

Leave a Reply