As suggested by other answers, using a StringBuilder
would probably be a better option.
The code given in the question will actually be compiled (with Sun's javac
) to something along the line of the following:
public static String concatStrings(Vector strings) {
String returnValue = "";
Iterator iter = strings.iterator();
while( iter.hasNext() ) {
String str = (String)iter.next();
StringBuilder sb = new StringBuilder(returnValue);
sb.append(str);
returnValue = sb.toString();
}
return returnValue;
}
The compiler will change the +=
string concatenation with one that uses a StringBuilder
. However, the compiler will probably rewrite the code inside the loop so a new StringBuilder
instance will be created on each iteration, which is not very performance-friendly.
Therefore, in this case, it would probably be a better idea to create a StringBuilder
outside the loop on our own, and perform manual string concatenation:
public static String concatStrings(Vector strings) {
StringBuidler returnValueBuilder;
Iterator iter = strings.iterator();
while( iter.hasNext() ) {
returnValueBuilder.append((String)iter.next());
}
return returnValueBuilder.toString();
}