3

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

Community
  • 1
  • 1
Ondrej Tokar
  • 4,898
  • 8
  • 53
  • 103

3 Answers3

9

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.

Fermin Silva
  • 3,331
  • 2
  • 17
  • 21
  • Consider allocating a larger initial capacity to your StringBuilder as well if building Strings over 16 characters long. `StringBuilder sb = new StringBuilder(1000);` – BoDidely Aug 07 '15 at 13:40
  • 1
    `it doesn't do it when the concatenation happens inside a loop` ??? any reference for this statement? – Suresh Atta Aug 07 '15 at 13:48
1

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()

Community
  • 1
  • 1
darijan
  • 9,725
  • 25
  • 38
0

Before going to the actual problem, see how internal concatenation works.

String testString ="str"+"ingcon"+"catenation";  

If we print the above declared String to console and see, the result is stringconcatenation.Which is correct and the + works fine. Here is out actual question, how does that + symbol did the magic ? ? Is it not a normal mathematical addition of Strings. The below code snippet shows how that code with + actually converts.

 StringBuilder compilerGeneratedBuilder = new StringBuilder();  
 compilerGeneratedBuilder.append("str");  
 compilerGeneratedBuilder.append("ingcon");  
 compilerGeneratedBuilder.append("catenation");  
 String finalString = compilerGeneratedBuilder.toString(); 

More .....

50K times loop is a descent performance blocker to consider.

In such cases use StringBuilder with append method. Cause concat (+) create a new object every time a new String Builder object. That leads to 50k objects creations.

With single StringBuilder and append method, you can save the time of Objection creation as well as the memory too.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • @JonathanDrapeau I'm talking about the run time behaviour of String concatination. : http://codeinventions.blogspot.in/2014/08/compiler-version-string-concatenation.html – Suresh Atta Aug 07 '15 at 13:44
  • @JonathanDrapeau It's not confusing at all. Under the hood, Java uses a `StringBuilder` to concat. When using it to concat multiple times, such as in a loop, a new builder is created each time, which leads to a performance impact – Vince Aug 07 '15 at 13:47
  • @JonathanDrapeau I am the author of that article :) Will add that. – Suresh Atta Aug 07 '15 at 13:49