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。
本文对比了StringBuffer和StringBuilder的特点及使用场景。StringBuffer线程安全但效率较低,适合多线程环境;StringBuilder非线程安全但效率较高,适用于单线程环境。两者在进行字符串拼接时的时间复杂度均为O(n)。
8482

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



