Re: StringBuilder
On 9/11/2011 10:35 AM, Wanja Gayk wrote:
In article<4e655caa$0$308$14726298@news.sunsite.dk>, arne@vajhoej.dk
says...
Whereby this code is slower:
String res="";
for (int i=0; i<100; i++) {
res+=i+"*"+i+"="+(i*i)+"\n";
}
System.out.println(res);
It is translated to the following code by the compiler, and
thus uses 100 new and 100 toString():
String res="";
for (int i=0; i<100; i++) {
StringBuilder _buf=new StringBuilder(res);
_buf.append(i);
_buf("*");
_buf.append(i);
_buf.append("=");
_buf.append((i*i));
_buf.append("\n");
res=_buf.toString();
}
System.out.println(res);
For more information see for example here:
http://caprazzi.net/posts/java-bytecode-string-concatenation-and-stringbuilder/
That has been known for 10-15 years.
It should be in any Java book above beginners level.
Like other ancient performance-practices that have been obsoleted by
today's compilers?
No.
What we are talking about is the "+=" part and that part is
still relevant for todays compilers.
Actually JB's example use = but to be equivalent to the first code
the it need to be +=.
And besides what he mention as reasons there are also
the 100 new strings.
We have been told that using StringBuffer was the better alternative.
Now compilers have switched from using StringBuffer for the above
example to the unsynchronized StringBuilder. Those who have manually
used the StringBuffer have stopped the compiler for doing that for them
and must rely on the JITs lock elision algorithm.
That is a little interesting quirk.
The outside loop string += part is more efficient with StringB*. And
I am pretty sure that the StringBuffer/StringBuilder difference
is negligible.
But the inside loop string + is probably a little bit faster
with StringBuilder than StringBuffer.
You can consider that insignificant compared to the first.
Or you could argue for using StringB* and append of string +.
So as long as this part of the code does not represent a critical
performance-bottleneck, I would recommend to use the simple, stupid
"slow" variant and hope for future compilers to detect and optimize that
pattern.
As long as it is not critical then readability should be the deciding
factor.
Arne