Why string concatenation takes so long time? [dupl

2019-02-20 01:46发布

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

3条回答
对你真心纯属浪费
2楼-- · 2019-02-20 02:29

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楼-- · 2019-02-20 02:39

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.

查看更多
太酷不给撩
4楼-- · 2019-02-20 02:46

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.

查看更多
登录 后发表回答