Friday, June 6, 2008

String Buffer vs StringBuilder vs Concatination Operator +

Run this code ... you will realize using concatination operator is better than stringBuilder
Most of us ( including me ) had the idea that StringBuilder will be fast



long now = System.currentTimeMillis();
for (int i=0; i<10000000; i++) {
String str = "one; two " +
";three four; five; six" +
"seven eight nine ten";
}
long then = System.currentTimeMillis();
System.out.println("+ " + Long.toString(then - now));

now = System.currentTimeMillis();
for (int i=0; i<10000000; i++) {
StringBuilder sb = new StringBuilder(200);
sb.append("one; two ");
sb.append(
";three four; five; six");
sb.append(
"seven eight nine ten");
String str = sb.toString();
}
then = System.currentTimeMillis();
System.out.println("StringBuilder " + Long.toString(then - now));

now = System.currentTimeMillis();
for (int i=0; i<10000000; i++) {
StringBuffer sb = new StringBuffer(200);
sb.append("one; two ");
sb.append(
";three four; five; six");
sb.append(
"seven eight nine ten");
String str = sb.toString();
}
then = System.currentTimeMillis();
System.out.println("String Buffer " + Long.toString(then - now));

Output on my PC was ...

+ 32
StringBuilder 9031
String Buffer 12125

4 comments:

Anonymous said...

Bro you got this thing a bit wrong. Change the String str = "one;two" + "three;four;" etc to

String str = "one;two";
str += "three;four;five";
str += "six;seven";

Then run your code and see for yourself whats better.

Internally String class makes use of the StringBuilder object. So there's no way String can be better than StringBuilder or for that matter even StringBuffer.

Lavnish said...

thanks for the correction bro ...
I changed the code to
String str = "one;two";
str += "three;four;five";
str += "six;seven";

and now the output is
+ 10360
StringBuilder 6171
String Buffer 11907

Looks like StringBuilder is clear winner ... and as far as choice between + operator and StringBuffer is considered obviously StringBuffer should be preferred.

wat say ??

Vaibhav Choudhary said...

yes, its correct ! StringBuilder is thread-unsafe and fast very similar difference like when you compare ArrayList and Vector.

I have checked that somewhere in March,2007 :

http://java4ever.blogspot.com/2007/03/string-vs-stringbuffer-vs-stringbuilder.html

Vaibhav Choudhary said...

One more news for you. You can now use the nanosecond functionality of JDK, so you need not to write 10000 loops :)