When two strings areconcatenated, the contents of both are copied.
String s1="adfasd";
String s2="oiuioqer";
s1=s1+s2;
也就是说s1,s2被拷贝到一块内存区然后合并再赋给一个新的内存区s1(新创建的一个对象)?几位朋友还是未明确说明
Item 33: Beware the performance of string concatenation
The string concatenation operator (+) is a convenient way to combine a few strings into one. It is fine for generating a single line of output or for constructing the string representation of a small, fixed-size object, but it does not scale. Using the string concatenation operator repeatedly to concatenate n strings requires time quadratic in n. It is an unfortunate consequence of the fact that strings are immutable (Item 13). When two strings areconcatenated, the contents of both are copied.
For example, consider the following method that constructs a string representation of a billing statement by repeatedly concatenating a line for each item:
// Inappropriate use of string concatenation - Performs horribly!
public String statement() {
String s = "";
for (int i = 0; i < numItems(); i++)
s += lineForItem(i); // String concatenation
return s;
}
This method performs abysmally if the number of items is large. To achieve acceptableperformance, use a StringBuffer in place of a String to store the statement underconstruction:
public String statement() {
StringBuffer s = new StringBuffer(numItems() * LINE_WIDTH);
for (int i = 0; i < numItems(); i++)
s.append(lineForItem(i));
return s.toString();
}
The difference in performance is dramatic. If numItems returns 100 and lineForItem returns a constant 80-character string, the second method is ninety times faster on my machine than the first. Because the first method is quadratic in the number of items and the second is linear, the performance difference is even more dramatic for larger numbers of items. Note that the second method preallocates a StringBuffer large enough to hold the result. Even if it is detuned to use a default-sized StringBuffer, it is still forty-five times faster than the first.
The moral is simple: Don't use the string concatenation operator to combine more than a few strings unless performance is irrelevant. Use StringBuffer's append method instead. Alternatively, use a character array, or process the strings one at a time instead of combining them.