09 January 2007

StringBuffer versus String

This is typic performace consideration in Java
If code is slow, developer starts tuning with using StringBuffer
therefore i find suitable to post this issue..

String str = " alem buysa";
str += "kral fener";

This is typic innocent usage of '+' for concatanation.

if StringBuffer is int. to be used than

StringBuffer str = new StringBuffer("alem buysa");
str.append("kral fener");

if you look without thinking(like ox),then i am pretty sure you will say
first one is more effective since we use only + in the second case
we are calling a function

but developers look code with thinking deeply

lets evaluate byte code of it

this is for String class
0 new #7
3 dup
4 ldc #2
6 invokespecial #12
9 astore_1
10 new #8
13 dup
14 aload_1
15 invokestatic #23
18 invokespecial #13
21 ldc #1
23 invokevirtual #15
26 invokevirtual #22
29 astore_1


and for string buffer

0 new #8
3 dup
4 ldc #2
6 invokespecial #13
9 astore_1
10 aload_1
11 ldc #1
13 invokevirtual #15
16 pop


as you see in + operation type casting to String Buffer calling function and again returning to String class kills the performance

StringBuffer has significant performance gain compare to String..
(To be honest , usage of + is so easy..)

1 comment:

Tonguç said...

Ufak bir onerim olacak; "Java Performance Tuning" Label altindaki uyarilarini orneklendirerek somutlastirirsan daha carpici olur bence Osman.