Android优化

Android优化(瘦身+代码+内存)

2017-03-01  本文已影响33人  wangyuchao

原文链接:https://yuchao.wang/article?id=37

应用瘦身

应用瘦身应用瘦身

代码分析

代码分析代码分析

内存优化

内存优化是Android应用优化最重要的一部分

内存分配

内存泄露

常见情景

    public static void main(String[] args) {
        ArrayList<Student> arrayList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Student student = new Student();
            student.name = i + "";
            arrayList.add(student);
            if (i == 2) {
                student = null;//没有释放内存,造成内存泄露
            }
        }
        System.out.println(arrayList.toString());
        arrayList.set(3, null);// 正确释放内存
        System.out.println(arrayList.toString());
    }
    
    // 结果如下
    [Student{name='0'}, Student{name='1'}, Student{name='2'}, Student{name='3'}, Student{name='4'}]
    [Student{name='0'}, Student{name='1'}, Student{name='2'}, null, Student{name='4'}]
public class Activity {
    private static Test test = null;

    class Test {
    }

    public void onCreate() {
        if (test == null) {
            test = new Test();
        }
    }
}

Android Monitors

MonitorsMonitors

点击Dump Java Heap 会自动打开 .hprof文件,可以查看如下图所示

hprof文件分析hprof文件分析 hprof文件分析hprof文件分析 hprof文件分析hprof文件分析

那么我们怎么才能发现内存泄露呢?这只是显示了一些基础的保留堆栈、总栈、层次、深度之类的参数,我们只能分析比较浅显容易看出来的内存泄露,比如某一个Bitmap占用了大量的内存,然后就可以 jump to source 。如果想要详细分析应用内存,这时就需要用到MAT了。

MAT 分析跟踪

hprof文件分析hprof文件分析 MATMAT MATMAT MATMAT

可以根据上图中引用个数判断是否内存泄露,如果引用个数过多,可能就会造成内存泄露。我们点击Histogram 查看一下 ArrayList

MATMAT MATMAT

通过对包名weiboyi的搜索发现,util 包中 GsonUtil 可能会有内存泄露,因为引用数量太多了。

下面我们再搜索一下activity,看是否存在Activity的泄露。可能我这运行次数比较少,目前还没有发现。

MATMAT

以上都仅仅是比较简单的用法,MAT的更多功能只能慢慢探索。

LeakCanary

如果你厌倦了上述的检测内存泄露的繁琐方式,那么现在有个开源类库LeakCanary,可以直接让内存泄露无所遁形。

具体的说明请看官网吧,LeakCanary中文说明在这

参考

上一篇下一篇

猜你喜欢

热点阅读