0%

为什么StringBuilder比拼接String高效

源码

  • String
    1
    2
    3
    4
    5
    public final class String implements java.io.Serializable, Comparable<String>,CharSequence {
    /** The value is used for character storage. */
    private final char value[];
    ...
    }
  • StringBulder(继承AbstractStringBuilder)
    1
    2
    3
    4
    5
    6
    7
    abstract class AbstractStringBuilder implements Appendable, CharSequence {
    /**
    * The value is used for character storage.
    */
    char[] value;
    ...
    }

结论

String中存储字符的是一个final修饰的char数组,所以每次拼接的时候都是重新生成一个String对象,都会进行数组的拷贝。而StringBulder中存储字符的char数组是可变的,当新的字符串长度大于当前容量的时候会进行数组拷贝。默认的capacity为16,每次扩容长度为当前value的长度的2倍+2:

1
2
3
4
5
6
7
8
9
10
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;
}