StringBuilder vs String concatenation in toString() in Java

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

    For simple strings like that I prefer to use

    "string".concat("string").concat("string");
    

    In order, I would say the preferred method of constructing a string is using StringBuilder, String#concat(), then the overloaded + operator. StringBuilder is a significant performance increase when working large strings just like using the + operator is a large decrease in performance (exponentially large decrease as the String size increases). The one problem with using .concat() is that it can throw NullPointerExceptions.

提交回复
热议问题