StringBuilder vs String concatenation in toString() in Java

后端 未结 18 2268
北恋
北恋 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:08

    I prefer:

    String.format( "{a: %s, b: %s, c: %s}", a, b, c );
    

    ...because it's short and readable.

    I would not optimize this for speed unless you use it inside a loop with a very high repeat count and have measured the performance difference.

    I agree, that if you have to output a lot of parameters, this form can get confusing (like one of the comments say). In this case I'd switch to a more readable form (perhaps using ToStringBuilder of apache-commons - taken from the answer of matt b) and ignore performance again.

提交回复
热议问题