StringBuilder vs String concatenation in toString() in Java

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

    I think we should go with StringBuilder append approach. Reason being :

    1. The String concatenate will create a new string object each time (As String is immutable object) , so it will create 3 objects.

    2. With String builder only one object will created[StringBuilder is mutable] and the further string gets appended to it.

提交回复
热议问题