1. 程式人生 > >Java 字串拼接 五種方法的效能比較分析 “+”、contact、join、append

Java 字串拼接 五種方法的效能比較分析 “+”、contact、join、append

一、五種方法分析:

1. 加號 “+”

2. String contact() 方法

3. StringUtils.join() 方法

4. StringBuffer append() 方法

5. StringBuilder append() 方法

二、優劣勢分析

開銷表(從執行100次到90萬次

1. 方法1 加號 “+” 拼接 和 方法2 String contact() 方法 適用於小資料量的操作,程式碼簡潔方便,加號“+” 更符合我們的編碼和閱讀習慣;

2. 方法3 StringUtils.join() 方法 適用於將ArrayList轉換成字串,就算90萬條資料也只需68ms,可以省掉迴圈讀取ArrayList的程式碼;

3. 方法4 StringBuffer append() 方法 和 方法5 StringBuilder append() 方法 其實他們的本質是一樣的,都是繼承自AbstractStringBuilder,效率最高,大批量的資料處理最好選擇這兩種方法。

4. 方法1 加號 “+” 拼接 和 方法2 String contact() 方法 的時間和空間成本都很高(下文分析),不能用來做批量資料的處理。

三、原始碼分析

1. 其實每次呼叫contact()方法就是一次陣列的拷貝,雖然在記憶體中是處理都是原子性操作,速度非常快,但是,最後的return語句會建立一個新String物件,限制了concat方法的速度。

public String concat(String str) {
        int otherLen = str.length();
        if (otherLen == 0) {
            return this;
        }
        int len = value.length;
        char buf[] = Arrays.copyOf(value, len + otherLen);
        str.getChars(buf, len);
        return new String(buf, true);
    }

2. StringBuffer 和 StringBuilder 的append方法都繼承自AbstractStringBuilder,整個邏輯都只做字元陣列的加長,拷貝,到最後也不會建立新的String物件,所以速度很快,完成拼接處理後在程式中用strBuffer.toString()來得到最終的字串。

    /**
     * Appends the specified string to this character sequence.
     * <p>
     * The characters of the {@code String} argument are appended, in
     * order, increasing the length of this sequence by the length of the
     * argument. If {@code str} is {@code null}, then the four
     * characters {@code "null"} are appended.
     * <p>
     * Let <i>n</i> be the length of this character sequence just prior to
     * execution of the {@code append} method. Then the character at
     * index <i>k</i> in the new character sequence is equal to the character
     * at index <i>k</i> in the old character sequence, if <i>k</i> is less
     * than <i>n</i>; otherwise, it is equal to the character at index
     * <i>k-n</i> in the argument {@code str}.
     *
     * @param   str   a string.
     * @return  a reference to this object.
     */
    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;
    }
    /**
     * This method has the same contract as ensureCapacity, but is
     * never synchronized.
     */
    private void ensureCapacityInternal(int minimumCapacity) {
        // overflow-conscious code
        if (minimumCapacity - value.length > 0)
            expandCapacity(minimumCapacity);
    }

    /**
     * This implements the expansion semantics of ensureCapacity with no
     * size check or synchronization.
     */
    void expandCapacity(int minimumCapacity) {
        int newCapacity = value.length * 2 + 2;
        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);
    }

3. 字串的加號“+” 方法, 雖然編譯器對其做了優化,使用StringBuilder的append方法進行追加,但是每迴圈一次都會建立一個StringBuilder物件,且都會呼叫toString方法轉換成字串,所以開銷很大。

  注:執行一次字串“+”,相當於 str = new StringBuilder(str).append("a").toString();

4. 本文開頭的地方統計了時間開銷,根據上述分析再想想空間的開銷。常說拿空間換時間,反過來是不是拿時間換到了空間呢,但是在這裡,其實時間是消耗在了重複的不必要的工作上(生成新的物件,toString方法),所以對大批量資料做處理時,加號“+” 和 contact 方法絕對不能用,時間和空間成本都很高。

搬運自大佬文章:

https://www.cnblogs.com/twzheng/p/5923642.html