This question already has an answer here:
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
You should use a
StringBuffer
or aStringBuilder
.When you add Strings with plus, a
StringBuilder
is created, strings are concatenated and a new String is return withtoString()
method of theStringBuilder
. So image this object creation and string manipulation 50k times. It's much better if you instantiate only oneStringBuilder
yourself and just append strings...This answer could be of use to you: concatenation operator (+) vs concat()
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:
Remark:
When you do stuff like
The compiler is smart enough to replace all that with a single
StringBuilder
, like:But for some reason I don't know, it doesn't do it when the concatenation happens inside a loop.
Before going to the actual problem, see how internal concatenation works.
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.
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.