Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Improving performance of string concatenation in Java [duplicate]

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;
}
like image 253
Rachel Avatar asked May 05 '10 01:05

Rachel


2 Answers

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.

like image 152
Andy White Avatar answered Oct 10 '22 20:10

Andy White


public static String concatStrings(List<String> strings) {
    StringBuilder sb = new StringBuilder();
    for (String s : strings) {
       sb.append(s);
    }    
    return sb.toString();
}

Some remarks:

  • Use StringBuilder whenever you need to build a string in a loop
    • + is fine for simple concatenation, but horrible for incremental build
  • Whenever possible, use for-each for readability
  • java.util.Vector is synchronized; if you don't need this (costly) feature, just use an ArrayList.

Don't use raw types

  • 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.

See also

  • Java string concatenation
  • Java Tutorials - Generics
like image 21
polygenelubricants Avatar answered Oct 10 '22 20:10

polygenelubricants