天天看點

String、StringBuilder、StringBuffer 用法比較

【本文轉載于http://blog.csdn.net/ithomer/article/details/7669843】

string

 簡要的說, string 類型和 stringbuffer 類型的主要性能差別其實在于 string 是不可變的對象, 是以在每次對 string 類型進行改變的時候其實都等同于生成了一個新的 string 對象,然後将指針指向新的 string 對象,是以經常改變内容的字元串最好不要用 string ,因為每次生成對象都會對系統性能産生影響,特别當記憶體中無引用對象多了以後, jvm 的 gc 就會開始工作,那速度是一定會相當慢的。

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.count = size;  

       this.value = v;  

public string(char value[]) {  

       int size = value.length;  

       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.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 ,特别是字元串對象經常改變的情況下。

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);  

public synchronized stringbuffer append(stringbuffer sb) {  

       super.append(sb);  

而在某些特别情況下, 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 要快。兩者的方法基本相同。

public stringbuilder() {  

public stringbuilder(int capacity) {  

public stringbuilder(string str) {  

public stringbuilder(charsequence seq) {  

public stringbuilder append(object obj) {  

       return append(string.valueof(obj));  

   public stringbuilder append(string str) {  

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;  

public stringbuilder append(stringbuffer sb) {  

在大部分情況下: stringbuilder > stringbuffer

總結

stringbuffer 和 stringbuilder 都繼承于 abstractstringbuilder 父類,實作了java.io.serializable, charsequence

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)       // 如果設定的最小容量 > 目前位元組存儲容量  

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) {  

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) {  

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());        // 傳回對象本身  

在大部分情況下,三者的效率如下:

stringbuilde > stringbuffer > string