博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android性能优化之内存优化练习
阅读量:6869 次
发布时间:2019-06-26

本文共 2048 字,大约阅读时间需要 6 分钟。

练习题目地址:https://github.com/lzyzsd/MemoryBugs

分析及优化过程如下:

问题1 静态变量引用activity

使用神器LeakCanary检查内存泄露问题

699960-20160409161333047-1964645652.png

从图中可以看到内存泄露的原因是静态的sTextView引用了mContext导致MainActivity的实例泄露.

所以解决方案也很简单,就是将sTextView改为非静态的变量.

经测试,通过.

问题2 大量创建不需要的对象

private void startAllocationLargeNumbersOfObjects() {        Toast.makeText(this, "请注意查看MemoryMonitor 以及AllocationTracker", Toast.LENGTH_SHORT).show();        for (int i = 0; i < 10000; i++) {            Rect rect = new Rect(0, 0, 100, 100);            System.out.println("-------: " + rect.width());        }    }

多次触发该方法,观察allocation Tracker

699960-20160409171526297-1488639103.png

由于此处大量创建了重复的对象,所以采用以下方案修改

Rect rect = null;    private void startAllocationLargeNumbersOfObjects() {        Toast.makeText(this, "请注意查看MemoryMonitor 以及AllocationTracker", Toast.LENGTH_SHORT).show();        for (int i = 0; i < 10000; i++) {//            Rect rect = new Rect(0, 0, 100, 100);            if(rect == null) {                rect =  new Rect(0, 0, 100, 100);            }            System.out.println("-------: " + rect.width());        }    }

效果有所改善

699960-20160409172500140-321200891.png

另外发现大量使用System.out.println("-------: " + rect.width());也相当的消耗内存

以下是将其注释掉的效果
699960-20160409172738859-1095686564.png

问题3 在onDraw方法中创建对象

@Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        RectF rect = new RectF(0, 0, 100, 100);        Paint paint = new Paint();        paint.setColor(Color.RED);        paint.setStrokeWidth(4);        canvas.drawArc(rect, 0, 180, true, paint);    }

androidstudio已经给出了提示:

Avoid object allocations during draw/layout operations (preallocate and reuse instead)

You should avoid allocating objects during a drawing or layout operation. These are called frequently, so a smooth UI can be interrupted by garbage collection pauses caused by the object allocations. The way this is generally handled is to allocate the needed objects up front and to reuse them for each drawing operation. Some methods allocate memory on your behalf (such as Bitmap.create), and these should be handled in the same way.

因为onDraw方法会被高频调用,所以在其中创建对象势必占用大量的内存,故应该避免这种情况的发生.

转载于:https://www.cnblogs.com/happyhacking/p/5372140.html

你可能感兴趣的文章
iOS-点击图片放大,再次点击返回原视图 类似查看相册的功能
查看>>
JAVA -- stateless4j StateMachine 使用浅析(二)
查看>>
oracle checkpoint
查看>>
KVM虚拟化开源高可用方案(六)ISCSI ON DRBD搭建及常见故障处理
查看>>
android device related
查看>>
iOS 6 Beta3即将发布,iPhone面板谍照已经曝光
查看>>
hadoop 源码包编译
查看>>
h5存储的优点
查看>>
Python基础之各种推导式玩法
查看>>
[HNOI/AHOI2017]影魔
查看>>
微信小程序-多级联动
查看>>
Ubuntu配置MYSQL远程连接
查看>>
docker-1-简介
查看>>
PAT 1020
查看>>
tcp端口扫描(python多线程)
查看>>
W3CSchool闯关笔记(Bootstrap)
查看>>
洛谷 P3742 umi的函数【构造】
查看>>
剑指offer-二叉树的镜像
查看>>
二叉树的创建,遍历完整代码
查看>>
java实现二叉树
查看>>