View RSS Feed

My Java Tips

Performance Issues (String Concatenation)

Rate this Entry
by , 11-09-2011 at 04:55 PM (1604 Views)
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:

Java Code:
String a=  "a";
String b=  "b";
String str = a + b;
This is compiled to

Java Code:
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.

Java Code:
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.

Java Code:
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 concatenate a String 10000 times with a String object: 140
Time to concatenate 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.

Submit "Performance Issues (String Concatenation)" to Facebook Submit "Performance Issues (String Concatenation)" to Digg Submit "Performance Issues (String Concatenation)" to del.icio.us Submit "Performance Issues (String Concatenation)" to StumbleUpon Submit "Performance Issues (String Concatenation)" to Google

Tags: None Add / Edit Tags
Categories
Performance

Comments