1:默认初始长度 16
public StringBuffer() {
super(16);
}
2:append追加
@Override public synchronized StringBuffer append(String str) { toStringCache = null; super.append(str); return this; }
public AbstractStringBuilder append(String str) { if (str == null) return appendNull(); int len = str.length(); ensureCapacityInternal(count + len); str.getChars(0, len, value, count); count += len; return this; }
private void ensureCapacityInternal(int minimumCapacity) { // overflow-conscious code if (minimumCapacity - value.length > 0) { value = Arrays.copyOf(value, newCapacity(minimumCapacity)); } }
每次长度补够时,都会调用Arrays.copy() ,在此之前,还要计算新的char[]长度 newCapacity(minimumCapacity)
private int newCapacity(int minCapacity) { // overflow-conscious code int newCapacity = (value.length << 1) + 2; if (newCapacity - minCapacity < 0) { newCapacity = minCapacity; } return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0) ? hugeCapacity(minCapacity) : newCapacity; }
新的长度=最小长度*2+2 (最小长度:追加字符串后需要占用的长度)
原文:https://www.cnblogs.com/draymond/p/12885367.html