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

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

问题描述

鉴于下面的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切换到builder吗?

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.

这篇关于StringBuilder vs Java中toString()的字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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