StringBuilder vs String concatenation in toString() in Java

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

    Make the toString method as readable as you possibly can!

    The sole exception for this in my book is if you can prove to me that it consumes significant resources :) (Yes, this means profiling)

    Also note that the Java 5 compiler generates faster code than the handwritten "StringBuffer" approach used in earlier versions of Java. If you use "+" this and future enhancements comes for free.

提交回复
热议问题