Why string concatenation takes so long time? [duplicate]

扶醉桌前 提交于 2019-12-01 09:27:49

问题


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


回答1:


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.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/31879096/why-string-concatenation-takes-so-long-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!