Java頻繁的進行字串拼接不要用 String! StringBuffer是最佳選擇!

好喜歡薩摩豬發表於2020-10-16

一個小demo直觀感受一下String的+是多麼的慢!

public class Main {
    public static void main(String[] args) {
        long begin = System.currentTimeMillis()/1000;
        String s = "";
        for(int i=0;i<1000000;i++){
            s += "123";
        }
        long end = System.currentTimeMillis()/1000;
        System.out.println("耗時"+(end-begin)+"秒");


        begin = System.currentTimeMillis()/1000;
        StringBuffer stringBuffer = new StringBuffer();
        for(int i=0;i<1000000;i++){
            stringBuffer.append("456");
        }
        end = System.currentTimeMillis()/1000;
        System.out.println("耗時"+(end-begin)+"秒");


        begin = System.currentTimeMillis()/1000;
        StringBuilder stringBuilder = new StringBuilder();
        for(int i=0;i<1000000;i++){
            stringBuilder.append("789");
        }
        end = System.currentTimeMillis()/1000;
        System.out.println("耗時"+(end-begin)+"秒");
    }
}

相關文章