|
Performance Issues (String Concatenation)
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.
<div class="wp_syntax"><div class="code">String s = new String(); long start = System.currentTimeMillis(); for(int i=0;i
|