Concatenate Strings into Java Loops - Stringbuilder or '+'?

Asked

Viewed 27,744 times

11

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

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

It’s a simple way to do the job, and much less verbose than with Stringbuilder.

But in cases of Loops like the 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));
}

1 answer

17


According to JSL - Java Specification Language

15.18.1. String Concatenation Operator +

The operator '+' offers the facility of being a single character to concatenate Strings, and its use is enconrajado. Actually when the compiler is compiled the compiler switches to a Stringbuilder

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

Why?

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

See how the code should look, compare the performance of both, is shocking, the 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

  • 4

    +1 And for those who are interested, I "decompiled" the codes above (slightly modified) and found that - in the bytecodes (compiled on Ubuntu - javac 1.7.0_79) - in fact a new StringBuilder is created with each loop iteration.

  • Yes, it’s amazing the compiler should infer a unique Stringbuilder.

  • Using Stringbuilder: Total time: 5,106,995 (nano Seconds) (5 million) Using '+': Total time: 4,192,903,645 (nano Seconds) (4 BILLION) Huge difference...

  • Very good. Vinvendo and learn"e"ndendo.

  • A curiosity: The sonarQube generates an Issue in concatenations within loops with + "In each iteration, the String is converted to a Stringbuffer/Stringbuilder, appended to, and converted back to a String. This can lead to a cost quadratic in the number of iterations, as the Growing string is recopied in each iteration. Better performance can be obtained by using a Stringbuffer (or Stringbuilder in Java 1.5) explicitly."

Browser other questions tagged

You are not signed in. Login or sign up in order to post.