Given the 2 toString() implementations below, which is prefered
public String toString(){
return "{a:"+ a + ", b:" + b + ", c: " + c +"}";
}
or
public String toString(){
StringBuilder sb = new StringBuilder(100);
return sb.append("{a:").append(a)
.append(", b:").append(b)
.append(", c:").append(c)
.append("}")
.toString();
}
More importantly given we have only 3 properties it might not make a difference, but at what point do you switch from concat to builder?
本文探讨了Java中两种不同的toString()实现方式:使用StringBuilder和字符串直接拼接,并讨论了何时应该选择哪种方法。结论指出,在循环中进行拼接时,推荐使用StringBuilder。
923

被折叠的 条评论
为什么被折叠?



