Java String Stringbuffer Stringbuilder

[quote]Mutability Difference:
String is immutable, if you try to alter their values, another object gets created, whereasStringBuffer and StringBuilder are mutable so they can change their values.
Thread-Safety Difference:
The difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe. So when the application needs to be run only in a single thread then it is better to useStringBuilder. StringBuilder is more efficient than StringBuffer.
Situations:

* If your string is not going to change use a String class because a String object is immutable.
* If your string can change (example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a StringBuilder is good enough.
* If your string can change, and will be accessed from multiple threads, use a StringBufferbecause StringBuffer is synchronous so you have thread-safety.
[/quote]
[b]对于可变性而言:[/b]
意思是说String是不可变的,如果要改变它们的值,就会创建新的对象。
而StringBuffer和StringBuilder是可变的,所以可以改变它们的值。
[b]对于线程安全而言:[/b]
StringBuffer是线程安全的,当应用程序只能运行在单线程的时候StringBuffer是优于StringBuffer的,当然这样的话StringBuilder的效率是高于StringBuffer的。
[b]应用场景:[/b]
如果string不会发生改变使用String,因为String是不可变的。
如果string发生改变,如果只能应用于单线程,那么StringBuilder就足够使用了。
如果string发生改变,应用于多线程场景,就需要考虑线程安全的因素,所以需要使用StringBuffer。因为StringBuffer是同步的。

参考资料:
http://stackoverflow.com/questions/2971315/string-stringbuffer-and-stringbuilder
http://kaioa.com/node/59
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值