Saturday, April 10, 2010

Difference Between String VS StringBuffer VS StringBuilder

Shown below is an example that concatanates 10000 strings using the '+' operator, StringBuffer, and StringBuilder, and prints the operation time in nanoseconds. The ability to get time in nanoseconds is another feature that was added in JDK 1.5.

public class StringConcatanations {
public static final int MAX_ITER = 10000;

public static void main(String[] args) {
concatenate();
concatenateWithStringBuffer();
concatenateWithStringBuilder();
}

public static void concatenate() {
System.out.println("Concatanating using the + operator");
String s1 = "";
long s1Time = getNanoTime();
for(int i=0;i) {
s1 = s1 + "abc";
}
long e1Time = getNanoTime();
System.out.println("Time: " + (e1Time - s1Time));
}

public static void concatenateWithStringBuffer() {
System.out.println("Concatanating using StringBuffer");
StringBuffer sb = new StringBuffer();
long s2Time = getNanoTime();
for(int i=0;i) {
sb.append("abc");
}
long e2Time = getNanoTime();
System.out.println("Time: " + (e2Time - s2Time));
}

public static void concatenateWithStringBuilder() {
System.out.println("Concatanating using StringBuilder");
StringBuilder sBuilder = new StringBuilder();
long s3Time = getNanoTime();
for(int i=0;i) {
sBuilder.append("abc");
}
long e3Time = getNanoTime();
System.out.println("Time: " + (e3Time - s3Time));
}

public static long getNanoTime() {
return System.nanoTime();
}

}


Output:
Concatanating using the + operator
Time: 744597428
Concatanating using StringBuffer
Time: 1685131
Concatanating using StringBuilder
Time: 1317206


Check out the time taken to append the String using "+" operator!!

As you can see, if you do not need thread safety, StringBuilder yeilds the best result, followed by Stringuffer, followed by the '+' operator. However, if you do need thread safety, then StringBuffer is your natural choice.

Cheers

Shyamala


1 comment:

  1. Fantastic post. you have indeed covered the topic with great details with stats and graph. I have also blogged my experience as String vs StringBuffer vs StringBuilder let me know how do you find it.

    ReplyDelete