String, StringBuffer, and StringBuilder

本文详细比较了String、StringBuilder和StringBuffer三种字符串类的区别。主要从可变性、线程安全性两个方面进行阐述,并针对不同场景提供了具体建议。

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

关于这三者的区别已经是老话题了,上stackoverflow看到目前最中肯简洁的回答


http://stackoverflow.com/a/2971343



Mutability Difference:

String is immutable, if you try to alter their values, another object gets created, whereas StringBuffer 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 use StringBuilderStringBuilder 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值