Tuesday, 1 July 2014

String Vs StringBuffer

1. String is immutable, i.e, the contents of the string are not changed after creation. Where as StringBuffer is mutable.

2. Performance wise, StringBuffer is faster when performing concatenations. This is because when you concatenate a String, you are creating a new Stirng object every time since String is immutable. So StringBuffer is preferrable while performing many concatenations.

Example
class StringVsStringBuffer{

 static void concatStrings(){
  String s = " ";
  String s1 = "a";
  for(int i=0; i < 100000; i++){
   s = s.concat(s1);
  }
 }
 
 static void concatStringBuffer(){
  StringBuffer s = new StringBuffer("");
  String s1 = "a";
  for(int i=0; i < 100000; i++){
   s.append(s1);
  }
 }
 
 public static void main(String args[]){
  long time1 = System.currentTimeMillis();
  concatStrings();
  long time2 = System.currentTimeMillis();
  concatStringBuffer();
  long time3 = System.currentTimeMillis();
  
  System.out.print("Time taken for String append is ");
  System.out.println((time2-time1) + " Milliseconds");
  System.out.print("Time taken for StringBuffer append is ");
  System.out.println((time3-time2) + " Milliseconds");
 }
}

Output
Time taken for String append is 2377 Milliseconds
Time taken for StringBuffer append is 4 Milliseconds





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment