问题描述
鉴于下面的 2 个 toString()
实现,哪个是首选:
Given the 2 toString()
implementations below, which one is preferred:
public String toString(){
return "{a:"+ a + ", b:" + b + ", c: " + c +"}";
}
或
public String toString(){
StringBuilder sb = new StringBuilder(100);
return sb.append("{a:").append(a)
.append(", b:").append(b)
.append(", c:").append(c)
.append("}")
.toString();
}
?
更重要的是,鉴于我们只有 3 个属性,这可能不会有什么不同,但是在什么时候您会从 +
concat 切换到 StringBuilder
?
More importantly, given we have only 3 properties it might not make a difference, but at what point would you switch from +
concat to StringBuilder
?
推荐答案
版本 1 更可取,因为它更短而且 编译器实际上会将其转换为版本 2 - 没有任何性能差异.
Version 1 is preferable because it is shorter and the compiler will in fact turn it into version 2 - no performance difference whatsoever.
更重要的是,我们只有 3 个它可能不会产生的属性不同,但你在什么时候从 concat 切换到构建器?
当您在循环中进行连接时 - 通常是编译器无法自行替换 StringBuilder
时.
At the point where you're concatenating in a loop - that's usually when the compiler can't substitute StringBuilder
by itself.
这篇关于Java 中 toString() 中的 StringBuilder 与字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!