Performance Issues (String Concatenation)

28 November 2007

String concatenation is a task that is overlooked by the programmers. In this post, I will write about the performance issues related to string concatenation.

Strings are immutable objects and to concatenate strings, java has to perform a lot of operations in the background. Consider the following code segment:

String a=  "a";
String b=  "b";
String str = a + b;

This is compiled to

String str = (new StringBuffer()).append(a).append(b).toString();

You can see that Java compiler has to do a lot while concatenating strings. If you know that you might need to append or concatenate strings with you string, then you should use StringBuffer.

StringBuffer str = new StringBuffer();
str.append(a);

Let do a test in order to understand the performance difference. We will append a string 10000 times with a String object
and
10000 times with StringBuffer object

Lets see how much time it takes.

String s = new String();
long start = System.currentTimeMillis();
 
for(int i=0;i<10000;i++)
   s += "a";
long stop = System.currentTimeMillis();
 
System.out.println("Time to concatinate a String 10000 times with a String object: " 
   + (stop - start));
 
StringBuffer stringBuffer = new StringBuffer();
start = System.currentTimeMillis();
 
for(int i=0;i<10000;i++)
   stringBuffer.append("a");
 
stop = System.currentTimeMillis();
 
System.out.println("Time to concatinate a String 10000 times with a StringBuffer object: " 
   + (stop - start));

Output:

Time to concatinate a String 10000 times with a String object: 140
Time to concatinate a String 10000 times with a StringBuffer object: 16

Difference is clear. I would like to conclude on the note that use String if you are sure that you wont need to change anything and use StringBuffer if you feel that you might need to change the value.

del.icio.us:Performance Issues (String Concatenation)  digg:Performance Issues (String Concatenation)  spurl:Performance Issues (String Concatenation)  wists:Performance Issues (String Concatenation)  simpy:Performance Issues (String Concatenation)  newsvine:Performance Issues (String Concatenation)  blinklist:Performance Issues (String Concatenation)  furl:Performance Issues (String Concatenation)  reddit:Performance Issues (String Concatenation)  fark:Performance Issues (String Concatenation)  blogmarks:Performance Issues (String Concatenation)  Y!:Performance Issues (String Concatenation)  smarking:Performance Issues (String Concatenation)  magnolia:Performance Issues (String Concatenation)  segnalo:Performance Issues (String Concatenation)  gifttagging:Performance Issues (String Concatenation)

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Performance Issues (String Concatenation)

Leave a Reply