Concatenate Strings in Java Loops-StringBuilder or'+'?

Java allows us to concatenate Strings in Java using only the ' + ' operator

String str = "a" + "b" + "c";

Is a simple way to get the job done, and much less verbose than with StringBuilder.

But in cases of Loops like the one below, which approach is the most performant?

' + ' or StringBuilder?

public static void main(String... args) {
        long initialTime = System.currentTimeMillis();

        String s = "a";

        for (int i = 0; i < 100000; i++) {
            s += "a";
        }

        System.out.println("Total time: " + (System.currentTimeMillis() - initialTime));
}
Author: Filipe Miranda, 2015-06-27

1 answers

According to jsl-Java Specification Language

15.18.1. String Concatenation Operator +

The ' + ' operator offers the ease of being a single character to concatenate Strings, and its use is complicated. Actually when compiling the compiler swaps for a StringBuilder

While this is a valuable feature, it should not be used in loops like the one in the question above.

Why?

A new StringBuilder it will be created at each iteration (with the initial value of str) and at the end of each iteration there will be concatenation with the initial String (actually StringBuilder with initial value of str). So, you should create StringBuilder ourselves only when we are concatenating Strings in loops.

See how the code should look, compare the performance of both, it's shocking, how faster the program gets:

public static void main(String... args) {
        long initialTime = System.currentTimeMillis();

        String s = "a";
        StringBuilder strBuilder = new StringBuilder(s);
        for (int i = 0; i < 100000; i++) {
            strBuilder.append("a");
        }

        System.out.println("Total time: " + (System.currentTimeMillis() - initialTime));
    }

Source: http://jknowledgecenter.blogspot.com.br/2015/05/always-use-stringbuilder-while.html

 16
Author: Filipe Miranda, 2015-06-28 00:11:23