字符串拼接性能对比

总是在思考为什么要用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就很容易阅读.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值