StringBuffer and String Builder

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值