StringBuffer Vs StringBuilder in Java

(Last Updated On: August 11, 2016)

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,

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));
}

}
}

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

 

 

 

147 total views, 1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *