选择合适的String拼接方法(这篇博客是我抄的)

package com.test;

public class FreeFile {

    public static void main(String[] args) {
        // 加号拼接
        String str = "";
        long start1 = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            str += "c";
        }
        long end1 = System.currentTimeMillis();
        System.out.println("加号拼接耗时:" + (end1 - start1) + "ms");

        // concat拼接
        str = "";
        long start2 = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            str = str.concat("c");
        }
        long end2 = System.currentTimeMillis();
        System.out.println("concat拼接耗时:" + (end2 - start2) + "ms");

        // StringBuilder拼接
        str = "";
        StringBuilder buffer = new StringBuilder("");
        long start3 = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            buffer.append("c");
        }
        long end3 = System.currentTimeMillis();
        System.out.println("StringBuilder拼接耗时:" + (end3 - start3) + "ms");

        // StringBuffer拼接
        str = "";
        StringBuffer sb = new StringBuffer("");
        long start4 = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            sb.append("c");
        }
        long end4 = System.currentTimeMillis();
        System.out.println("StringBuffer拼接耗时:" + (end4 - start4) + "ms");

    }

}

原文地址:https://www.cnblogs.com/wgbs25673578/p/5882210.html