欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java字符串拼接的五種方法及性能比較分析(從執(zhí)行100次到90萬次)

 更新時(shí)間:2021年12月17日 10:24:57   作者:老壇酸菜WH  
字符串拼接一般使用“+”,但是“+”不能滿足大批量數(shù)據(jù)的處理,Java中有以下五種方法處理字符串拼接及性能比較分析,感興趣的可以了解一下

> 字符串拼接一般使用“+”,但是“+”不能滿足大批量數(shù)據(jù)的處理,Java中有以下五種方法處理字符串拼接,各有優(yōu)缺點(diǎn),程序開發(fā)應(yīng)選擇合適的方法實(shí)現(xiàn)。

1. 加號(hào) “+”

2. String contact() 方法

3. StringUtils.join() 方法

4. StringBuffer append() 方法

5. StringBuilder append() 方法

> 經(jīng)過簡單的程序測試,從執(zhí)行100次到90萬次的時(shí)間開銷如下表:

?由此可以看出:

1. 方法1 加號(hào) “+” 拼接 和 方法2 String contact() 方法 適用于小數(shù)據(jù)量的操作,代碼簡潔方便,加號(hào)“+” 更符合我們的編碼和閱讀習(xí)慣;

2. 方法3 StringUtils.join() 方法 適用于將ArrayList轉(zhuǎn)換成字符串,就算90萬條數(shù)據(jù)也只需68ms,可以省掉循環(huán)讀取ArrayList的代碼;

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

4. 方法1 加號(hào) “+” 拼接 和 方法2 String contact() 方法 的時(shí)間和空間成本都很高(分析在本文末尾),不能用來做批量數(shù)據(jù)的處理。

> 源代碼,供參考

package cnblogs.twzheng.lab2;

/**
 * @author Tan Wenzheng
 *
 */
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

public class TestString {

    private static final int max = 100;

    public void testPlus() {
        System.out.println(">>> testPlus() <<<");

        String str = "";

        long start = System.currentTimeMillis();

        for (int i = 0; i < max; i++) {
            str = str + "a";
        }

        long end = System.currentTimeMillis();

        long cost = end - start;

        System.out.println("   {str + \"a\"} cost=" + cost + " ms");
    }

    public void testConcat() {
        System.out.println(">>> testConcat() <<<");

        String str = "";

        long start = System.currentTimeMillis();

        for (int i = 0; i < max; i++) {
            str = str.concat("a");
        }

        long end = System.currentTimeMillis();

        long cost = end - start;

        System.out.println("   {str.concat(\"a\")} cost=" + cost + " ms");
    }

    public void testJoin() {
        System.out.println(">>> testJoin() <<<");

        long start = System.currentTimeMillis();

        List<String> list = new ArrayList<String>();

        for (int i = 0; i < max; i++) {
            list.add("a");
        }

        long end1 = System.currentTimeMillis();
        long cost1 = end1 - start;

        StringUtils.join(list, "");

        long end = System.currentTimeMillis();
        long cost = end - end1;

        System.out.println("   {list.add(\"a\")} cost1=" + cost1 + " ms");
        System.out.println("   {StringUtils.join(list, \"\")} cost=" + cost
                + " ms");
    }

    public void testStringBuffer() {
        System.out.println(">>> testStringBuffer() <<<");

        long start = System.currentTimeMillis();

        StringBuffer strBuffer = new StringBuffer();

        for (int i = 0; i < max; i++) {
            strBuffer.append("a");
        }
        strBuffer.toString();

        long end = System.currentTimeMillis();

        long cost = end - start;

        System.out.println("   {strBuffer.append(\"a\")} cost=" + cost + " ms");
    }

    public void testStringBuilder() {
        System.out.println(">>> testStringBuilder() <<<");

        long start = System.currentTimeMillis();

        StringBuilder strBuilder = new StringBuilder();

        for (int i = 0; i < max; i++) {
            strBuilder.append("a");
        }
        strBuilder.toString();

        long end = System.currentTimeMillis();

        long cost = end - start;

        System.out
                .println("   {strBuilder.append(\"a\")} cost=" + cost + " ms");
    }
}

> 測試結(jié)果:

1. 執(zhí)行100次, private static final int max = 100;

>>> testPlus() <<<
   {str + "a"} cost=0 ms
>>> testConcat() <<<
   {str.concat("a")} cost=0 ms
>>> testJoin() <<<
   {list.add("a")} cost1=0 ms
   {StringUtils.join(list, "")} cost=20 ms
>>> testStringBuffer() <<<
   {strBuffer.append("a")} cost=0 ms
>>> testStringBuilder() <<<
   {strBuilder.append("a")} cost=0 ms

2. 執(zhí)行1000次, private static final int max = 1000;

>>> testPlus() <<<
   {str + "a"} cost=10 ms
>>> testConcat() <<<
   {str.concat("a")} cost=0 ms
>>> testJoin() <<<
   {list.add("a")} cost1=0 ms
   {StringUtils.join(list, "")} cost=20 ms
>>> testStringBuffer() <<<
   {strBuffer.append("a")} cost=0 ms
>>> testStringBuilder() <<<
   {strBuilder.append("a")} cost=0 ms

3. 執(zhí)行1萬次, private static final int max = 10000;

>>> testPlus() <<<
   {str + "a"} cost=150 ms
>>> testConcat() <<<
   {str.concat("a")} cost=70 ms
>>> testJoin() <<<
   {list.add("a")} cost1=0 ms
   {StringUtils.join(list, "")} cost=30 ms
>>> testStringBuffer() <<<
   {strBuffer.append("a")} cost=0 ms
>>> testStringBuilder() <<<
   {strBuilder.append("a")} cost=0 ms

4. 執(zhí)行10萬次, private static final int max = 100000;

>>> testPlus() <<<
   {str + "a"} cost=4198 ms
>>> testConcat() <<<
   {str.concat("a")} cost=1862 ms
>>> testJoin() <<<
   {list.add("a")} cost1=21 ms
   {StringUtils.join(list, "")} cost=49 ms
>>> testStringBuffer() <<<
   {strBuffer.append("a")} cost=10 ms
>>> testStringBuilder() <<<
   {strBuilder.append("a")} cost=10 ms

5. 執(zhí)行20萬次, private static final int max = 200000;

>>> testPlus() <<<
   {str + "a"} cost=17196 ms
>>> testConcat() <<<
   {str.concat("a")} cost=7653 ms
>>> testJoin() <<<
   {list.add("a")} cost1=20 ms
   {StringUtils.join(list, "")} cost=51 ms
>>> testStringBuffer() <<<
   {strBuffer.append("a")} cost=20 ms
>>> testStringBuilder() <<<
   {strBuilder.append("a")} cost=16 ms

6. 執(zhí)行50萬次, private static final int max = 500000;

>>> testPlus() <<<
   {str + "a"} cost=124693 ms
>>> testConcat() <<<
   {str.concat("a")} cost=49439 ms
>>> testJoin() <<<
   {list.add("a")} cost1=21 ms
   {StringUtils.join(list, "")} cost=50 ms
>>> testStringBuffer() <<<
   {strBuffer.append("a")} cost=20 ms
>>> testStringBuilder() <<<
   {strBuilder.append("a")} cost=10 ms

7. 執(zhí)行90萬次, private static final int max = 900000;

>>> testPlus() <<<
   {str + "a"} cost=456739 ms
>>> testConcat() <<<
   {str.concat("a")} cost=186252 ms
>>> testJoin() <<<
   {list.add("a")} cost1=20 ms
   {StringUtils.join(list, "")} cost=68 ms
>>> testStringBuffer() <<<
   {strBuffer.append("a")} cost=30 ms
>>> testStringBuilder() <<<
   {strBuilder.append("a")} cost=24 ms

> 查看源代碼,以及簡單分析

String contact 和 StringBuffer,StringBuilder 的源代碼都可以在Java庫里找到,有空可以研究研究。

1. 其實(shí)每次調(diào)用contact()方法就是一次數(shù)組的拷貝,雖然在內(nèi)存中是處理都是原子性操作,速度非???,但是,最后的return語句會(huì)創(chuàng)建一個(gè)新String對(duì)象,限制了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,整個(gè)邏輯都只做字符數(shù)組的加長,拷貝,到最后也不會(huì)創(chuàng)建新的String對(duì)象,所以速度很快,完成拼接處理后在程序中用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. 字符串的加號(hào)“+” 方法, 雖然編譯器對(duì)其做了優(yōu)化,使用StringBuilder的append方法進(jìn)行追加,但是每循環(huán)一次都會(huì)創(chuàng)建一個(gè)StringBuilder對(duì)象,且都會(huì)調(diào)用toString方法轉(zhuǎn)換成字符串,所以開銷很大。

  注:執(zhí)行一次字符串“+”,相當(dāng)于 str = new StringBuilder(str).append("a").toString();

4. 本文開頭的地方統(tǒng)計(jì)了時(shí)間開銷,根據(jù)上述分析再想想空間的開銷。常說拿空間換時(shí)間,反過來是不是拿時(shí)間換到了空間呢,但是在這里,其實(shí)時(shí)間是消耗在了重復(fù)的不必要的工作上(生成新的對(duì)象,toString方法),所以對(duì)大批量數(shù)據(jù)做處理時(shí),加號(hào)“+” 和 contact 方法絕對(duì)不能用,時(shí)間和空間成本都很高。

到此這篇關(guān)于Java字符串拼接的五種方法及性能比較分析(從執(zhí)行100次到90萬次)的文章就介紹到這了,更多相關(guān)Java字符串拼接內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!?

相關(guān)文章

  • Java String 和StringBuffer的詳解及區(qū)別

    Java String 和StringBuffer的詳解及區(qū)別

    這篇文章主要介紹了Java String 和StringBuffer的詳解及區(qū)別的相關(guān)資料,需要的朋友可以參考下
    2017-05-05
  • Java實(shí)現(xiàn)插入排序,希爾排序和歸并排序

    Java實(shí)現(xiàn)插入排序,希爾排序和歸并排序

    這篇文章主要為大家詳細(xì)介紹了插入排序,希爾排序和歸并排序的多種語言的實(shí)現(xiàn)(JavaScript、Python、Go語言、Java),感興趣的小伙伴可以了解一下
    2022-12-12
  • 如何基于Autowired對(duì)構(gòu)造函數(shù)進(jìn)行注釋

    如何基于Autowired對(duì)構(gòu)造函數(shù)進(jìn)行注釋

    這篇文章主要介紹了如何基于Autowired對(duì)構(gòu)造函數(shù)進(jìn)行注釋,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-10-10
  • Java rmi遠(yuǎn)程方法調(diào)用基本用法解析

    Java rmi遠(yuǎn)程方法調(diào)用基本用法解析

    這篇文章主要介紹了Java rmi遠(yuǎn)程方法調(diào)用基本用法解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-05-05
  • SpringBoot實(shí)現(xiàn)自定義線程池的方法

    SpringBoot實(shí)現(xiàn)自定義線程池的方法

    這篇文章主要介紹了SpringBoot中的自定義線程池解析,實(shí)現(xiàn)自定義線程池重寫spring默認(rèn)線程池的方式使用的時(shí)候,只需要加@Async注解就可以,不用去聲明線程池類,需要的朋友可以參考下
    2023-11-11
  • spring cloud gateway轉(zhuǎn)發(fā)服務(wù)報(bào)錯(cuò)的解決

    spring cloud gateway轉(zhuǎn)發(fā)服務(wù)報(bào)錯(cuò)的解決

    這篇文章主要介紹了spring cloud gateway轉(zhuǎn)發(fā)服務(wù)報(bào)錯(cuò)的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • java之Timer和TimerTask簡單demo(分享)

    java之Timer和TimerTask簡單demo(分享)

    下面小編就為大家?guī)硪黄猨ava之Timer和TimerTask簡單demo(分享)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2016-12-12
  • Java面向?qū)ο笾蓡T隱藏與屬性封裝操作示例

    Java面向?qū)ο笾蓡T隱藏與屬性封裝操作示例

    這篇文章主要介紹了Java面向?qū)ο笾蓡T隱藏與屬性封裝操作,結(jié)合實(shí)例形式分析了Java面向?qū)ο蟪绦蛟O(shè)計(jì)中成員的隱藏及屬性封裝相關(guān)實(shí)現(xiàn)與使用操作技巧,需要的朋友可以參考下
    2018-06-06
  • 淺談多線程中的鎖的幾種用法總結(jié)(必看)

    淺談多線程中的鎖的幾種用法總結(jié)(必看)

    下面小編就為大家?guī)硪黄獪\談多線程中的鎖的幾種用法總結(jié)(必看)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-05-05
  • Spring Boot 文件上傳與下載的示例代碼

    Spring Boot 文件上傳與下載的示例代碼

    這篇文章主要介紹了Spring Boot 文件上傳與下載的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03

最新評(píng)論