Android内存抖动分析
2017-09-09 本文已影响297人
选一个昵称这么难
1.为什么会内存抖动
简单说就是在短时间内有大量的gc操作
2.举个例子
public class MainActivity extends AppCompatActivity {
private String result = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt = (Button) findViewById(R.id.bt);
//点击按钮进行字符串拼接操作
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
for (int i = 0; i < 1000000; i++) {
result = result +i;
}
}
});
}
}
点击按钮进行字符串的拼接
我们知道String 类型的变量是不变的
比如
String value1 = "a";//创建一个对象指向value1
value1 = value1 + "b";//再次创建一个对象指向value1
上面的例子循环了1000000次,就会创建1000000个对象,这么多对象创建出来又被回收势必会引起内存抖动,我们通过日志或者monitors可以分析出来
com.dgtech.myapplication I/art: Background sticky concurrent mark sweep GC freed 26(864B) AllocSpace objects, 35(19MB) LOS objects, 18% free, 12MB/15MB, paused 5.530ms total 23.313ms
com.dgtech.myapplication I/art: Background sticky concurrent mark sweep GC freed 31(1040B) AllocSpace objects, 41(23MB) LOS objects, 0% free, 76MB/76MB, paused 5.250ms total 40.184ms
com.dgtech.myapplication I/art: Background partial concurrent mark sweep GC freed 114(3KB) AllocSpace objects, 159(104MB) LOS objects, 7% free, 50MB/54MB, paused 1.995ms total 107.696ms
com.dgtech.myapplication I/art: Background partial concurrent mark sweep GC freed 36(1048B) AllocSpace objects, 42(29MB) LOS objects, 6% free, 59MB/63MB, paused 13.771ms total 57.703ms
com.dgtech.myapplication I/art: Background sticky concurrent mark sweep GC freed 14(480B) AllocSpace objects, 17(12MB) LOS objects, 1% free, 15MB/15MB, paused 5.508ms total 12.141ms
com.dgtech.myapplication I/art: Background sticky concurrent mark sweep GC freed 20(672B) AllocSpace objects, 27(19MB) LOS objects, 0% free, 16MB/16MB, paused 5.435ms total 19.526ms
当有大量日志连续打印以上类似内容时,说明内存有抖动,我们需要检查代码,或者使用更直观的方式来看:
Monitors从Monitors的监控来看,内存一开始是平稳的,当点击拼接字符串的按钮后变开始抖动
注:有的时候我们无法选择要调试的程序,就像这样:
异常情况这个时候我们需要选择tools - Android - Enable ADB Integration