Java Reference
In-Depth Information
String answer = integerPart + "." + mantissa ;
That code is actually quite performant; the syntactic sugar of the javac compiler turns that
statement into this code:
String answer = new
new StringBuilder ( integerPart ). append ( "." ).
append ( mantissa ). toString ();
Problems arise, though, if the string is constructed piecemeal:
String answer = integerPart ;
answer += "." ;
answer += mantissa ;
That code translates into:
String answer = new
new StringBuilder ( integerPart ). toString ();
answer = new
new StringBuilder ( answer ). append ( "." ). toString ();
answer = new
new StringBuilder ( answer ). append ( mantissa ). toString ();
All those temporary StringBuilder and intermediate String objects are inefficient. Never
construct strings using concatenation unless it can be done on a single (logical) line, and nev-
er use string concatenation inside a loop unless the concatenated string is not used on the
next loop iteration. Otherwise, always explicitly use a StringBuilder object for better per-
formance. In Chapter 1 , I argued that there are times to “prematurely” optimize when that
phrase is used in a context meaning simply “write good code.” This is a prime example.
QUICK SUMMARY
1. One-line concatenation of strings yields good performance.
2. For multiple concatenation operations, make sure to use a StringBuilder .
Search WWH ::




Custom Search