String字符串拼接效率比較

字符串進行拼接有三種方法:加號、contact方法和StringBufferStringBuilder,StringBufferStringBuilder拼接方法相似,只是StringBuilder用於單線程,StringBuffer是線程安全的,用於多線程。

主要探討一下以上三種拼接方法的效率,當然大概效率都是知道的,如下

StringBuffer>concat>”>”

雖然知道這個結果,但是也更得知道所以然。

1.+”方法拼接字符串

雖然編譯器對字符串的加號做了優化,它會使用StringBuilderappend方法進行追加,那麼按道理來說,它的執行時間也應該和StringBuilder差不多啊,但是不然,實際實現如下:

Str=new StringBuilder(str).append(“c”).toString();

它每次拼接都會創建一個StringBuilder對象,並且還要調用toString()方法將其轉換爲字符串,這樣性能就大大降低了。

2.concat方法拼接字符串

首先看下源碼:

public String concat(String str){
        int otherLen = str.length();
        //如果追加的字符串長度爲0,則返回字符串本身
        if(otherLen == 0){
            return this;
        }
        //字符數組,容納的是新字符串的字符
        char buf[] = new char[count + otherLen];
        //取出原始字符串放到buf數組中
        getChars(0, count, buf, 0);
        //追加的字符串轉換成字符數組,添加到buf中
        str.getChars(0, otherLen, buf, count);
        //複製字符數組,產生一個新的字符串
        return new String(0, count + otherLen, buf);
    }
        



整體上看上去就是一個數組拷貝,雖然在內存中的處理都是原子性操作,速度非常快,但是最後一句return,每次的concat操作都會創建一個String對象,這樣就會讓concat的速度慢下來。

3.StringBuilder.append()方法拼接

源碼如下:

public AbstractStringBuilder append(String str){
        //如果爲null值,則把null作爲字符串處理
        if(str==null) str = "null";
        int len = str.length();
        //字符長度爲0,則返回本身
        if(len == 0) return this;
        int newCount = count +len;
        //追加後的字符數組長度是否超過當前值
        if(newCount > value.length()){
            //加長,並做數組拷貝
            expanCapacity(newCount);
        }
        //字符串複製到目標數組
        str.getChars(0, len, value, count);
        count = newCount;
        return this;
    }



整個append方法都在做字符數組處理,加長,然後數組拷貝,這些都是基本的數據處理,沒有創建任何對象,所以速度是非常快的。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章