Java Reference
In-Depth Information
concatenating two String literals involves creating a new String object and having the old
ones get garbage collected. For example, concatenating ” “ , ”Fai” , and ”ry” results in four
String objects being instantiated and three of them eligible for garbage collection immedi-
ately, as Figure 4.1 shows.
FIGURE 4.1 String concatenation can result in multiple String objects created and
garbage collected.
Initial expression
Intermediate String object
Final result
" " "Fai" "ry"
" Fai"
" Fairy"
The circled String objects are eligible for garbage
collection once the result is evaluated.
Optimizing String Concatenation
It is possible that a Java implementation optimizes String concatenation to minimize the
number of intermediate String objects created. The Java Language Specifi cation con-
tains the following statement:
An implementation may choose to perform conversion and
concatenation in one step to avoid creating and then discarding an
intermediate String object. To increase the performance of repeated
string concatenation, a Java compiler may use the StringBuffer class
or a similar technique to reduce the number of intermediate String
objects that are created by evaluation of an expression.
In other words, a JVM may or may not optimize String concatenation. Even if the JVM
does optimize this step, a temporary StringBuffer object is created behind the scenes.
Either way, you should avoid the overuse of String concatenation because it can be inef-
fi cient, especially when building strings or modifying them regularly. In these situations,
a StringBuffer or StringBuilder object is a better choice, which we discuss in the next
section.
See if you can determine how many String objects appear in memory from the follow-
ing statements:
10. String alpha = “”;
11. for(char current = 'a'; current <= 'z'; current++) {
12. alpha += current;
13. }
14. System.out.println(alpha);
 
Search WWH ::




Custom Search