字符串拼接性能比较出乎意料的结果

 一直认为String拼接大字符串时用StringBuffer能比直接用+号性能更高,今天偶然发现不竟然,是有前提的。如果String对象没用重新赋值,而是一次性把字符串拼接好赋值给String变量时性能是最高的(第二个例子String2)。如果String使用的是+=重新赋值,这时性能确实要比StringBuffer慢2-3倍左右(第一个例子String1)。

public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            String result = "This is ";
            result += "testing the";
            result += "difference between";
            result += "String and StringBuffer";
        }
        long endTime = System.currentTimeMillis();
        System.out.println(String.format("String+ 1 cost: %s millis", (endTime - startTime)));

        startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            String result = "This is" + "testing the" + "difference" + "between" + "String" + "and" + "StringBuffer";
        }
        endTime = System.currentTimeMillis();
        System.out.println(String.format("String+ 2  cost: %s millis", (endTime - startTime)));

        startTime = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            StringBuffer sbResult = new StringBuffer();
            sbResult.append("This is ");
            sbResult.append("testing the");
            sbResult.append("difference between");
            sbResult.append("String and StringBuffer");
            sbResult.toString();
        }
        endTime = System.currentTimeMillis();
        System.out.println(String.format("StringBuffer cost: %s millis", (endTime - startTime)));
    }

 

运行结果:

 

posted @ 2017-08-20 20:43  鼠标滚轮  阅读(171)  评论(0编辑  收藏  举报