Published June 15th, 2008
String goes StringBuffer
Let me first tell you what is StringBuilder. StringBuilder is a class analogous to StringBuffer added in JDK 1.5. This class is designed to use in place where StringBuffer is used by single thread(like in most
of the cases). According to documentation, StringBuilder should work faster than StringBuffer. So ” thread unsafe, fast”.
I was reading one of the posts of orkut Java community asking “what is this capacity in StringBuffer and even we can add two strings from String class why to go for StringBuffer”. Valid question ! GC need to work little more in case of String, but thats fair.
No don’t use String class for concatenation operation, always use StringBuffer / StringBuilder and let me tell you why ?
This is a simple Java code for string addition in String and StringBuffer:
class StringTest {
public static void main(String[] args)
{
String s = “just a string”;
s = s + “add me too”;
System.out.println(s);
/*
StringBuffer s = new StringBuffer(”just a string”);
//StringBuilder s = new StringBuilder(”just a string”);
s = s.append(”add me too”);
System.out.println(s);
*/
}
}
Alright, now have a look on the bytecode of this program.
>> javac StringTest.java
>> javap -c StringTest
Compiled from “StringTest.java” class StringTest extends java.lang.Object{ StringTest(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object.“:()V 4: return public static void main(java.lang.String[]); Code: 0: ldc #2; //String just a string 2: astore_1 3: new #3; //class java/lang/StringBuilder 6: dup 7: invokespecial #4; //Method java/lang/StringBuilder.“:()V 10: aload_1 11: invokevirtual #5; //Method java/lang/StringBuilder.append:(Ljava/lang/ String;)Ljava/lang/StringBuilder; 14: ldc #6; //String add me too 16: invokevirtual #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;) Ljava/lang/StringBuilder; 19: invokevirtual #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String; 22: astore_1 23: getstatic #8; //Field java/lang/System.out:Ljava/io/PrintStream; 26: aload_1 27: invokevirtual #9; //Method java/io/PrintStream.println:(Ljava/lang/String;)V 30: return }
Just see line no. 11. Interesting, the plus sign we used for addition is not as innocent as it looks. String itself use StringBuffer(StringBuilder) to add two strings and hence taking much more time than normal append operation done by StringBuffer. Let me give you more evidence, run verbose option and check the time
>> javac -verbose StringTest.java
and check the other one, that is, with StringBuffer one.
You can clearly figure out the time difference and make a try with StringBuilder, time should reduce furthermore.











Java,JavaScript,Threading,
Optimization and more with Vaibhav 


