String、StringBuilder、StringBuffer 三個類源自JDK的 java/lang/ 目錄下:
String 字串常量
StringBuffer 字串變數(安全執行緒)
StringBuilder 字串變數(非安全執行緒,JDK 5.0(1.5.0) 後支援)
String
簡要的說, String 類型和 StringBuffer 類型的主要效能區別其實在於 String 是不可變的對象, 因此在每次對 String 類型進行改變的時候其實都等同於產生了一個新的 String 對象,然後將指標指向新的 String 對象,所以經常改變內容的字串最好不要用 String ,因為每次產生對象都會對系統效能產生影響,特別當記憶體中無引用對象多了以後, JVM 的 GC 就會開始工作,那速度是一定會相當慢的。
String 建構函式:
private final char value[]; private final int offset; private final int count;public String() { this.offset = 0; this.count = 0; this.value = new char[0]; }public String(String original) { int size = original.count; char[] originalValue = original.value; char[] v; if (originalValue.length > size) { // The array representing the String is bigger than the new // String itself. Perhaps this constructor is being called // in order to trim the baggage, so make a copy of the array. int off = original.offset; v = Arrays.copyOfRange(originalValue, off, off+size); } else { // The array representing the String is the same // size as the String, so no point in making a copy. v = originalValue; } this.offset = 0; this.count = size; this.value = v; }public String(char value[]) { int size = value.length; this.offset = 0; this.count = size; this.value = Arrays.copyOf(value, size); }public String(char value[], int offset, int count) { if (offset < 0) { throw new StringIndexOutOfBoundsException(offset); } if (count < 0) { throw new StringIndexOutOfBoundsException(count); } // Note: offset or count might be near -1>>>1. if (offset > value.length - count) { throw new StringIndexOutOfBoundsException(offset + count); } this.offset = 0; this.count = count; this.value = Arrays.copyOfRange(value, offset, offset+count); }public String substring(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } if (endIndex > count) { throw new StringIndexOutOfBoundsException(endIndex); } if (beginIndex > endIndex) { throw new StringIndexOutOfBoundsException(endIndex - beginIndex); } return ((beginIndex == 0) && (endIndex == count)) ? this : new String(offset + beginIndex, endIndex - beginIndex, value);// 返回新對象 }public String concat(String str) { int otherLen = str.length(); if (otherLen == 0) { return this; } char buf[] = new char[count + otherLen]; getChars(0, count, buf, 0); str.getChars(0, otherLen, buf, count); return new String(0, count + otherLen, buf);// 返回新對象 }public static String valueOf(char data[]) { return new String(data);// 返回新對象 }public static String valueOf(char c) { char data[] = {c}; return new String(0, 1, data);// 返回新對象 }
StringBuffer
StringBuffer 每次對對象本身進行操作,而不是產生新的對象,再改變對象引用。所以在一般情況下我們推薦使用 StringBuffer ,特別是字串對象經常改變的情況下。
StringBuffer 建構函式:
public StringBuffer() { super(16); }public StringBuffer(int capacity) { super(capacity); }public StringBuffer(String str) { super(str.length() + 16); append(str); }public StringBuffer(CharSequence seq) { this(seq.length() + 16); append(seq); }public synchronized int length() {// 位元組實際長度 return count; }public synchronized int capacity() {// 位元組儲存容量(value數組的長度) return value.length; }public synchronized void ensureCapacity(int minimumCapacity) { if (minimumCapacity > value.length) { expandCapacity(minimumCapacity); } }public synchronized StringBuffer append(Object obj) { super.append(String.valueOf(obj)); return this;// 返回對象本身 }public synchronized StringBuffer append(String str) { super.append(str); return this;// 返回對象本身 }public synchronized StringBuffer append(StringBuffer sb) { super.append(sb); return this;// 返回對象本身 }
而在某些特別情況下, String 對象的字串拼接其實是被 JVM 解釋成了 StringBuffer 對象的拼接,所以這些時候 String 對象的速度並不會比 StringBuffer 對象慢,而特別是以下的字串對象產生中, String 效率是遠要比 StringBuffer 快的:
String S1 = “This is only a” + “ simple” + “ test”;
StringBuffer Sb = new StringBuilder(“This is only a”).append(“ simple”).append(“ test”);
你會很驚訝的發現,產生 String S1 對象的速度簡直太快了,而這個時候 StringBuffer 居然速度上根本一點都不佔優勢。其實這是 JVM 的一個把戲,在 JVM 眼裡,這個
String S1 = “This is only a” + “ simple” + “test”;
其實就是:
String S1 = “This is only a simple test”;
所以當然不需要太多的時間了。但大家這裡要注意的是,如果你的字串是來自另外的 String 對象的話,速度就沒那麼快了,譬如:
String S2 = “This is only a”;
String S3 = “ simple”;
String S4 = “ test”;
String S1 = S2 +S3 + S4;
這時候 JVM 會規規矩矩的按照原來的方式去做
在大部分情況下: StringBuffer > String
Java.lang.StringBuffer安全執行緒的可變字元序列。一個類似於 String 的字串緩衝區,但不能修改。雖然在任意時間點上它都包含某種特定的字元序列,但通過某些方法調用可以改變該序列的長度和內容。
可將字串緩衝區安全地用於多個線程。可以在必要時對這些方法進行同步,因此任意特定執行個體上的所有操作就好像是以串列順序發生的,該順序與所涉及的每個線程進行的方法調用順序一致。
StringBuffer 上的主要操作是 append 和 insert 方法,可重載這些方法,以接受任意類型的資料。每個方法都能有效地將給定的資料轉換成字串,然後將該字串的字元追加或插入到字串緩衝區中。append 方法始終將這些字元添加到緩衝區的末端;而 insert 方法則在指定的點添加字元。
例如,如果 z 引用一個當前內容是“start”的字串緩衝區對象,則此方法調用 z.append("le") 會使字串緩衝區包含“startle”,而 z.insert(4, "le") 將更改字串緩衝區,使之包含“starlet”。
StringBuilder
java.lang.StringBuilder一個可變的字元序列是5.0新增的。此類提供一個與 StringBuffer 相容的 API,但不同步。該類被設計用作 StringBuffer 的一個簡易替換,用在字串緩衝區被單個線程使用的時候(這種情況很普遍)。如果可能,建議優先採用該類,因為在大多數實現中,它比 StringBuffer 要快。兩者的方法基本相同。
StringBuilder 建構函式:
public StringBuilder() { super(16); }public StringBuilder(int capacity) { super(capacity); }public StringBuilder(String str) { super(str.length() + 16); append(str); }public StringBuilder(CharSequence seq) { this(seq.length() + 16); append(seq); }public StringBuilder append(Object obj) { return append(String.valueOf(obj)); } public StringBuilder append(String str) { super.append(str); return this;// 返回對象本身 }private StringBuilder append(StringBuilder sb) { if (sb == null) return append("null"); int len = sb.length(); int newcount = count + len; if (newcount > value.length) expandCapacity(newcount); sb.getChars(0, len, value, count); count = newcount; return this;// 返回對象本身 }public StringBuilder append(StringBuffer sb) { super.append(sb); return this;// 返回對象本身 }
在大部分情況下: StringBuilder > StringBuffer
總結
StringBuffer 和 StringBuilder 都繼承於 AbstractStringBuilder 父類,實現了java.io.Serializable, CharSequence
AbstractStringBuilder 父類建構函式:
char[] value;// 字元數組AbstractStringBuilder() { }AbstractStringBuilder(int capacity) { value = new char[capacity];// 申請位元組儲存容量 }public int length() { return count;// 返回實際位元組長度 }public int capacity() { return value.length;// 返回位元組儲存容量 }public void ensureCapacity(int minimumCapacity) { if (minimumCapacity > 0) ensureCapacityInternal(minimumCapacity);// 擴充容量大小 }private void ensureCapacityInternal(int minimumCapacity) { // overflow-conscious code if (minimumCapacity - value.length > 0)// 如果設定的最小容量 > 當前位元組儲存容量 expandCapacity(minimumCapacity); }void expandCapacity(int minimumCapacity) { int newCapacity = value.length * 2 + 2;// 自動新增容量,為當前容量的2倍加2(java是unicode編碼,佔兩個位元組) if (newCapacity - minimumCapacity < 0) newCapacity = minimumCapacity; if (newCapacity < 0) { if (minimumCapacity < 0) // overflow throw new OutOfMemoryError(); newCapacity = Integer.MAX_VALUE; } value = Arrays.copyOf(value, newCapacity); }public AbstractStringBuilder append(Object obj) { return append(String.valueOf(obj)); }public AbstractStringBuilder append(String str) { if (str == null) str = "null"; int len = str.length(); ensureCapacityInternal(count + len); str.getChars(0, len, value, count); count += len; return this;// 返回對象本身 }public AbstractStringBuilder append(StringBuffer sb) { if (sb == null) return append("null"); int len = sb.length(); ensureCapacityInternal(count + len); sb.getChars(0, len, value, count); count += len; return this;// 返回對象本身 }public AbstractStringBuilder append(CharSequence s) { if (s == null) s = "null"; if (s instanceof String) return this.append((String)s); if (s instanceof StringBuffer) return this.append((StringBuffer)s); return this.append(s, 0, s.length());// 返回對象本身 }
關於String更多的介紹,請詳見我先前寫的部落格:Java 之 String 類型
在大部分情況下,三者的效率如下:
StringBuilde > StringBuffer > String
參考推薦:
StringBuilder、StringBuffer、String 的區別
Java 之 String 類型