Java 中 toString() 中的 StringBuilder 与字符串连接 [英] StringBuilder vs String concatenation in toString() in Java

查看:25
本文介绍了Java 中 toString() 中的 StringBuilder 与字符串连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于下面的 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 切换到构建器?

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?

当您在循环中进行连接时 - 通常是编译器无法自行替换 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 与字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆