Performance Issues (String Concatenation)
28 November 2007String 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.
Related Posts:
- Javap - II
- Java built-in data types (performance issues)
- Java IO tasks
- Java performance Issues (I)
- Performance Issues (StringTokenizer)
- Performance Issues (adding element to a Vector)
- Vector Capacity
- Performance issues related to trigonometric functions , floating point arithmetic and JNI (I)
- Java performance Issues (III) - Garbage collection
- Java performance Issues (IV) - Hardware interfacing
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)