每当我用+运算符拼接字符串时, 总有人跟我提出你应该用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.
否则可以直接使用+以方便阅读.