StringBuffer
A thread-safe, mutable sequence of characters. A string buffer is like a
String
, but can be modified. 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.
StringBuilder
A mutable sequence of characters. This class provides an API compatible with
StringBuffer
, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for
StringBuffer
in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to
StringBuffer
as it will be faster under most implementations.
也就是说,StringBuffer是线程安全的,StringBuilder不是线程安全的,当然StringBuilder效率更高一些。
当向StringBuffer或StringBuilder中append字符时,效率为O(n). 因为实际上插入数据的方式是:copy所有的元素,加上插入的元素后,创建一个新的instance。