Java Reference
In-Depth Information
13.4. The StringBuilder Class
If immutable strings were the only kind available, you would have to
create a new String object for each intermediate result in a sequence
of String manipulations. Consider, for example, how the compiler would
evaluate the following expression:
public static String guillemete(String quote) {
return '«' + quote + '»';
}
If the compiler were restricted to String expressions, it would have to do
the following:
quoted = String.valueOf('«').concat(quote)
.concat(String.valueOf('»'));
Each valueOf and concat invocation creates another String object, so this
operation would construct four String objects, of which only one would
be used afterward. The others strings would have incurred overhead to
create, to set to proper values, and to garbage collect.
The compiler is more efficient than this. It uses a StringBuilder object to
build strings from expressions, creating the final String only when ne-
cessary. StringBuilder objects can be modified, so new objects are not
needed to hold intermediate results. With StringBuilder , the previous
string expression would be represented as
quoted = new StringBuilder().append('«')
.append(quote).append('»').toString();
 
Search WWH ::




Custom Search