2.12 Use Stringbuffer Instead of String Concatenation
The
String
class is the most commonly used class in Java.
Especially in Web applications, it is used extensively to generate and
format HTML content.
String
is designed to be immutable; in order to modify a String
, you have to create a new String
object. Therefore, string concatenation can result in creating many intermediate String
objects before the final String
can be constructed. StringBuffer
is the mutable companion class of String
; it allows you to modify the String
. Therefore, StringBuffer
is generally more efficient than String
when concatenation is needed.
This section also features the following practices:
- Use StringBuffer Instead of String Concatenation If You Repeatedly Append to a String In Multiple Statements
- Use Either String or StringBuffer If the Concatenation Is Within One Statement
- Use StringBuffer Instead of String Concatenation If You Know the Size of the String
2.12.1 Use StringBuffer Instead of String Concatenation If You Repeatedly Append to a String In Multiple Statements
Using the "+=" operation on a
String
repeatedly is expensive.
For example:
String s = new String(); [do some work ...] s += s1; [do some more work...] s += s2;
Replace the above string concatenation with a StringBuffer:
StringBuffer strbuf = new StringBuffer(); [do some work ...] strbuf.append(s1); [so some more work ...] strbuf.append(s2); String s = strbuf.toString();
2.12.2 Use Either String or StringBuffer If the Concatenation Is Within One Statement
String
and StringBuffer
perform the same in some cases; so you do not need to use StringBuffer
directly.
String s = "a" + "b" + "c"; to String s = "abc";
Optimization is done automatically by the compiler.
- The Java2 compiler will automatically collapse the above.
- The Java2 compiler will also automatically convert the following:
String s = s1 + s2; to String s = (new StringBuffer()).append(s1).append(s2).toString();
In these cases, there is no need to useStringBuffer
directly.
2.12.3 Use StringBuffer Instead of String Concatenation If You Know the Size of the String
The default character buffer for
StringBuffer
is 16. When
the buffer is full, a new one has to be re-allocated (usually at twice
the size of the original one). The old buffer will be released after the
content is copied to the new one. This constant reallocation can be
avoided if the StringBuffer is created with a buffer size that is big
enough to hold the String
.
The following will be more efficient than using a
String
concatenation.
String s = (new StringBuffer(1024)). append(s1).append(s2). toString();
will be faster than
String s = s1 + s2;
Nenhum comentário:
Postar um comentário