字符串拼接性能对比

总是在思考为什么要用MessageFormat.format,如果只是简单的拼接效率高还是使用format效率高:

转https://blog.csdn.net/cockroach02/article/details/53925119,完善了部分.

public static void main(String[] args) {

        int count = 10000000;

        long start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            String s = "Hi " + i + "; Hi to you " + i * 2;
        }
        long end = System.currentTimeMillis();
        System.out.println("Concatenation = " + ((end - start)) + " millisecond");


        start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            String s = String.format("Hi %s; Hi to you %s", i, +i * 2);
        }
        end = System.currentTimeMillis();
        System.out.println("Format = " + ((end - start)) + " millisecond");


        start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            String s = MessageFormat.format("Hi %s; Hi to you %s", i, +i * 2);
        }
        end = System.currentTimeMillis();
        System.out.println("MessageFormat%s = " + ((end - start)) + " millisecond");

        start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            String s = MessageFormat.format("Hi {0}; Hi to you {1}", i, +i * 2);
        }
        end = System.currentTimeMillis();
        System.out.println("MessageFormat${} = " + ((end - start)) + " millisecond");

        start = System.currentTimeMillis();
        for (int i = 0; i < count; i++) {
            StringBuilder bldString = new StringBuilder("Hi ");
            bldString.append(i).append("; Hi to you ").append(i * 2).toString();
        }
        end = System.currentTimeMillis();
        System.out.println("StringBuilder = " + ((end - start)) + " millisecond");

    }

执行结果:
Concatenation = 785 millisecond
Format = 10036 millisecond
MessageFormat%s = 2298 millisecond
MessageFormat${} = 21874 millisecond
StringBuilder = 903 millisecond
发现字符串拼接的效率并不低的.但是为什么要使用MessageFormat.format方法呢?
原来,format的方法是相当于占位符的,这样格式和参数很好的能够理解.
举个栗子:
有时候返回前端一个列表的时候,需要我们自己返回前端的代码;
String[] tdArr=…;
String result=MessageFormat.format("{0}{1}{2}{3}", tdArr);
如果一个一个拼接,就会不方便阅读,使用MessageFormat.format就很容易阅读.

posted @ 2019-09-17 11:43  你就像甜甜的益达  阅读(125)  评论(0编辑  收藏  举报