java的字符串拼接

 

每当我用+运算符拼接字符串时, 总有人跟我提出你应该用StringBuffer.

我真的希望提建议的人先看看String类的源代码, 从JavaSE6开始, 通过+运算符拼接字符串就是用StringBuilder或者StringBuffer类和他们的append()方法来实现的.

 

原话如下:

From java.lang.String source code:

 

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java. For additional information on string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification.

 

 

但是, 这种实现只是依赖于Javac的语法糖解析的, 编译后的class代码对于字符串+的拼接并没有做优化,

所以执行效率上将, 语法糖解析后的+拼接的代码依然达不到StringBuilder或者StringBuffer那样的速度.

具体讨论可以参考这篇帖子的讨论:

http://www.iteye.com/topic/1040986

 

所以具体到实际情况时:

对于需要大量使用的字符串拼接的情况(比如在循环中), 最好使用StringBuilder或者StringBuffer.

否则可以直接使用+以方便阅读.

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值