StringBuilder vs String concatenation in toString() in Java

后端 未结 18 2214
北恋
北恋 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 04:59

    Since Java 1.5, simple one line concatenation with "+" and StringBuilder.append() generate exactly the same bytecode.

    So for the sake of code readability, use "+".

    2 exceptions :

    • multithreaded environment : StringBuffer
    • concatenation in loops : StringBuilder/StringBuffer

提交回复
热议问题