Possible Duplicate:
java String concatenation
How to Improve performance of this chunk of code :
public static String concatStrings(Vector strings) {
String returnValue = "";
Iterator iter = strings.iterator();
while( iter.hasNext() ) {
returnValue += (String)iter.next();
}
return returnValue;
}
You might look at using StringBuilder, rather than doing += with the individual strings. Strings are immutable in Java, which means that once you create a String object, you cannot modify it. Using += on strings in a loop will result in the creation of many separate String instances, which may create performance problems. StringBuilder can concatenate Strings without having to create new instances, which may save some time, depending on the exact scenario.
public static String concatStrings(List<String> strings) {
StringBuilder sb = new StringBuilder();
for (String s : strings) {
sb.append(s);
}
return sb.toString();
}
Some remarks:
StringBuilder
whenever you need to build a string in a loop
+
is fine for simple concatenation, but horrible for incremental buildjava.util.Vector
is synchronized
; if you don't need this (costly) feature, just use an ArrayList
.JLS 4.8 Raw Types
The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.
Effective Java 2nd Edition: Item 23: Don't use raw types in new code
If you use raw types, you lose all the safety and expressiveness benefits of generics.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With