Java performance tips – Part 2 : Better String handling

StringBuffer vs String

As we all know both String & StringBuffer are used to hold string (character sequence) values. The basic & the most important difference between the objects being created using String & StringBuffer : objects of String are immutable (means, no one can change it); but the objects created using StringBuffer are mutable. Consider the following code block,

// Example 1 
String aString = "Hello"; 
aString = aString + "World !";
// Example 2 
StringBuffer aStringBuffer = new StringBuffer("Hello"); 
aStringBuffer.append("World !");

Here both example 1 & 2 are doing the same thing. If someone ask us which one we think is a better way to append a string to other, hmmm… sometimes, no most of the times people may choose the first method. B’ coz the “+” operator seems super cool, right?

The String concatenation using the “+” works in a crazy way. It will internally create a temporary StringBuffer object using the current value and will use the append() to get the things done. Why? Any guess? Yeah, you are right. B’ coz the object created using String is immutable.

I found the byte-code equivalent of both the string concatenation from javaworld.com. Let’s have a look at it.

Byte-code equivalent of example 1:

0 new #7 <Class java.lang.String> 
3 dup 
4 ldc #2 <String "Hello"> 
6 invokespecial #12 <Method java.lang.String(java.lang.String)> 
9 astore_1 
10 new #8 <Class java.lang.StringBuffer> 
13 dup 
14 aload_1 
15 invokestatic #23 <Method java.lang.String valueOf(java.lang.Object)> 
18 invokespecial #13 <Method java.lang.StringBuffer(java.lang.String)> 
21 ldc #1 <String "World !"> 
23 invokevirtual #15 <Method java.lang.StringBuffer append(java.lang.String)> 
26 invokevirtual #22 <Method java.lang.String toString()> 
29 astore_1

Byte-code equivalent of example 2:

0 new #8 <Class java.lang.StringBuffer> 
3 dup 
4 ldc #2 <String "Hello"> 
6 invokespecial #13 <Method java.lang.StringBuffer(java.lang.String)> 
9 astore_1 
10 aload_1 
11 ldc #1 <String "World !"> 
13 invokevirtual #15 <Method java.lang.StringBuffer append(java.lang.String)> 
16 pop

I donno how to interpret it. But we can easily understand what is happening there, right?

StringBuffer vs StringBuilder

StringBuilder is same as StringBuffer but not thread-safe. All the public methods of StringBuffer are synchronized. StringBuilder offers better performance than StringBuffer in most of the conditions. StringBuffer is advised to use only if some kind of synchronization is needs.

Advertisements