概要
String、StringBuffer、StringBuilder是常用的字符序列,从源码上对比下,三者的区别
类结构
String

StringBuffer

StringBuilder

- 都实现了
interface CharSequence,interface Comparable<T>,interface Serializable StringBuilder,StringBuffer继承了abstract class AbstractStringBuilder
CharSequence: A CharSequence is a readable sequence of char values. This interface provides uniform, read-only access to many different kinds of char sequences.
Comparable: This interface imposes a total ordering on the objects of each class that implements it.This ordering is referred to as the class's NATURAL ORDERING, and the class's compareTo method is referred to as its natural comparison method
Serializable: Serializability of a class is enabled by the class implementing the java.io.Serializable interface.
AbstractStringBuilder: A MUTABLE SEQUENCE of characters. Implements a modifiable string. At any point in time it contains some particular sequence of characters, but the length and content of the sequence CAN BE CHANGED through certain method calls.
Appendable:An object to which char sequences and values can be appended.
数据结构
String

final
StringBuffer、StringBuilder
在java.lang.AbstractStringBuilder中:
通过继承java.lang.Appendable支持修改
设计目标
String
StringBuffer
StringBuilder
无参构造函数
String
StringBuffer、StringBuilder
在java.lang.AbstractStringBuilder中:
默认byte[]初始化长度时16,调用append方法时,长度不够,会扩容,进行数组复制。
已知内容的情况下,可以通过指定长度,来避免扩容、减少数组复制。


一般情况下,可以不用考虑这么多,性能要求严格的情况下,需要考虑减少数组复制。
Arrays.copyOf底层是java.lang.System#arraycopy,arraycopy在JVM层面,会有更高效的方法替代。

总结
- String 初始化后不可修改,StringBuilder、StringBuffer支持修改。
- 操作少量的数据或者常量使用 String
- 单线程操作字符串缓冲区下操作大量数据,使用StringBuilder
- 多线程操作字符串缓冲区下操作大量数据,使用StringBuffer
- 性能严格要求的场景下,StringBuilder、StringBuffer可以通过指定初始化容量,减少数组复制
1528

被折叠的 条评论
为什么被折叠?



