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

8

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

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

It's a simple way to do the job, and much less verbose than using StringBuilder.

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

'+' 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));
}
    
asked by anonymous 27.06.2015 / 14:53

1 answer

13

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 their use is matched. In fact when compiling the compiler exchange for a StringBuilder

Although this is a valuable resource, it should not be used in loops like the one above.

Why?

A new StringBuilder 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, we should create StringBuilder ourselves only when we are concatenating strings in loops.

See how the code should look, compare their performance, it's shocking, how much 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: link

    
27.06.2015 / 14:53