Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why string concatenation takes so long time? [duplicate]

I am concatenating a String in a loop but it takes ages, why is that?

for (String object : jsonData) {
    counter++;
    finalJsonDataStr += object;
}

Variable object is a piece of JSON, up to 70 chars and the loop goes approx 50k times.

I understand some people advice StringBuffer or StringBuilder but this link says, it has no performance improvements: StringBuilder vs String concatenation in toString() in Java

like image 957
Ondrej Tokar Avatar asked Dec 09 '25 18:12

Ondrej Tokar


2 Answers

Use a String Builder to append to strings.

When you concatenate, Java is actually creating a new String with the results of the concatenation. Do it multiple times and you are creating gazillion of strings for nothing.

Try:

StringBuilder sb = new StringBuilder();
for (String object : jsonData) { 
    counter++; 
    sb.append(object.toString());  //this does the concatenation internally
                                   //but is very efficient
}

finalJsonDataStr = sb.toString(); //this gives you back the whole string 

Remark:

When you do stuff like

myString = "hello " + someStringVariable + " World!" + " My name is " + name;

The compiler is smart enough to replace all that with a single StringBuilder, like:

myString = new StringBuilder("hello ")
                      .append(someStringVariable)
                      .append(" World!")
                      .append(" My name is ")
                      .append(name).toString();

But for some reason I don't know, it doesn't do it when the concatenation happens inside a loop.

like image 196
Fermin Silva Avatar answered Dec 11 '25 07:12

Fermin Silva


You should use a StringBuffer or a StringBuilder.

When you add Strings with plus, a StringBuilder is created, strings are concatenated and a new String is return with toString() method of the StringBuilder. So image this object creation and string manipulation 50k times. It's much better if you instantiate only one StringBuilder yourself and just append strings...

This answer could be of use to you: concatenation operator (+) vs concat()

like image 44
darijan Avatar answered Dec 11 '25 08:12

darijan