StringBuilder与StringBuffer与String与的区别

三者的区别主要在两个方面:执行速度与线程安全方面

速度:StringBuilder > StringBuffer > String

为什么String的速度慢呢?String是字符常量,StringBuilder和StringBuffer都是字符变量

安全:StringBuffer是线程安全的

1、查看StringBuffer源码(部分)可见

 * A thread-safe, mutable sequence of characters.
 * 
 * //String buffers 是多线程安全的。
 * String buffers are safe for use by multiple threads. The methods
 * are synchronized where necessary so that all the operations on any
 * particular instance behave as if they occur in some serial order
 * that is consistent with the order of the method calls made by each of
 * the individual threads involved.

同时,可以看到大量synchronized修饰的方法。

2、查看StringBuilder源码(部分)可见

//StringBuilder的实例在多线程中不安全
<p>Instances of {@code StringBuilder} are not safe for
 * use by multiple threads. If such synchronization is required then it is
 * recommended that {@link java.lang.StringBuffer} be used.

3、String

 * Strings are constant; their values cannot be changed after they
 * are created. String buffers support mutable strings.
 * Because String objects are immutable they can be shared. For example:
 * 
 *     String str = "abc";
 * 
 * is equivalent to:
 *
 *     char data[] = {'a', 'b', 'c'};
 *     String str = new String(data);
 * 
 * Here are some more examples of how strings can be used:
 * 
 *     System.out.println("abc");
 *     String cde = "cde";
 *     System.out.println("abc" + cde);
 *     String c = "abc".substring(2,3);
 *     String d = cde.substring(1, 2);
 * 
 * 

Java中的String,StringBuilder,StringBuffer三者的区别(详细描述):http://www.cnblogs.com/su-feng/p/6659064.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jerryzhou;

您的鼓励,将是我的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值