结论
相同点:
- 都继承自
AbstractStringBuilder
- 都是可变长字符串,底层都是调用的
AbstractStringBuilder
的char[] value;
数组来存储,
stringBuffer
和stringBuilder
默认长度都是16。长度不够会进行扩容。
不同点:
stringBuffer
是线程安全的,每个公开方法上都有加锁synchronized
stringBuilder
不是线程安全的,公开方法没有加锁。
stringBuffer
里面有一个缓存toStringCache
,这是一个优化,在每次添加其他操作前都会将该缓存置为null
,stringBuilder
没有缓存
源码
stringBuilder
关键源码
public final class StringBuilder
extends AbstractStringBuilder
implements java.io.Serializable, CharSequence
{}
public StringBuilder() {
super(16);
}
public StringBuilder(int capacity) {
super(capacity);
}
public StringBuilder(String str) {
super(str.length() + 16);
append(str);
}
@Override
public StringBuilder append(Object obj) {
return append(String.valueOf(obj));
}
@Override
public StringBuilder append(String str) {
super.append(str);
return this;
}
toString
@Override
public String toString() {
// Create a copy, don't share the array
return new String(value, 0, count);
}
stringBuffer
关键源码
public final class StringBuffer
extends AbstractStringBuilder
implements java.io.Serializable, CharSequence
{}
public StringBuffer() { // stringbuffer默认容量是16,也可以自己指定
super(16);
}
public StringBuffer(int capacity) {
super(capacity);
}
public StringBuffer(String str) {
super(str.length() + 16);
append(str);
}
@Override
public synchronized int length() {
return count;
}
@Override
public synchronized int capacity() {
return value.length;
}
@Override
public synchronized StringBuffer append(Object obj) {
toStringCache = null;
super.append(String.valueOf(obj));
return this;
}
@Override
public synchronized StringBuffer append(String str) {
toStringCache = null;
super.append(str);
return this;
}
toString
@Override
public synchronized String toString() {
if (toStringCache == null) {
toStringCache = Arrays.copyOfRange(value, 0, count);
}
return new String(toStringCache, true);
}