StringBuilder vs String concatenation in toString() in Java

后端 未结 18 2181
北恋
北恋 2020-11-21 04:18

Given the 2 toString() implementations below, which one is preferred:

public String toString(){
    return \"{a:\"+ a + \", b:\" + b + \", c: \"         


        
18条回答
  •  北海茫月
    2020-11-21 05:00

    Performance wise String concatenation using '+' is costlier because it has to make a whole new copy of String since Strings are immutable in java. This plays particular role if concatenation is very frequent, eg: inside a loop. Following is what my IDEA suggests when I attempt to do such a thing:

    General Rules:

    • Within a single string assignment, using String concatenation is fine.
    • If you're looping to build up a large block of character data, go for StringBuffer.
    • Using += on a String is always going to be less efficient than using a StringBuffer, so it should ring warning bells - but in certain cases the optimisation gained will be negligible compared with the readability issues, so use your common sense.

    Here is a nice Jon Skeet blog around this topic.

提交回复
热议问题