<Android提高>String拼接性能分析

  String拼接在频繁使用时,不同方法性能差别较大:

package com.example.ss.hello;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView)findViewById(R.id.hello);
        long n = 10000;

        long start1 = System.currentTimeMillis();
        String s1 = new String("hello");
        for (long i = 0; i < n; i++)
        {
            s1 += "拼接--";
        }
        long end1 = System.currentTimeMillis();
        long time1 = end1 - start1;
        tv.setText("用String+=拼接字符串的时间:" + time1);

        long start2 = System.currentTimeMillis();
        String s2 = new String("hello");
        for (long i = 0; i < n; i++)
        {
            s2 = s2 + "拼接--";
        }
        long end2 = System.currentTimeMillis();
        long time2 = end2 - start2;
        tv.append("用String=String+拼接字符串的时间" + time2);

        long start3 = System.currentTimeMillis();
        String s3 = new String("hello");
        for (long i = 0; i < n; i++)
        {
            s3 = s3.concat("拼接--");
        }
        long end3 = System.currentTimeMillis();
        long time3 = end3 - start3;
        tv.append("用String.concat拼接字符串的时间" + time3);

        long start4 = System.currentTimeMillis();
        StringBuffer s4 = new StringBuffer("hello");
        for (long i = 0; i < n; i++)
        {
            s4.append("拼接--");
        }
        long end4 = System.currentTimeMillis();
        long time4 = end4 - start4;
        tv.append("用StringBuffer.append拼接字符串的时间" + time4);

        long start5 = System.currentTimeMillis();
        StringBuilder s5 = new StringBuilder("hello");
        for (long i = 0; i < n; i++)
        {
            s5.append("拼接--");
        }
        long end5 = System.currentTimeMillis();
        long time5 = end5 - start5;
        tv.append("用StringBuilder.append拼接字符串的时间" + time5);
    }
}

真机运行结果如下


可见使用+= 与使用StringBuilder.append差别达到了指数级。

频繁使用拼接的操作中若使用+=,则有可能造成频繁GC,从而产生丢帧的现象。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值