flutter内存泄漏检测

https://www.jianshu.com/p/f875c61b680f

通过Observatory分析内存泄漏

Observatory是官方提供的调试工具,通过dart vm获取运行时信息,通过它我们可以分析一系列性能相关数据,例如app耗时统计,代码覆盖率等,这里我们重点介绍内存相关的调试工具。(DevTools也可以用来调试分析性能数据,它是在Observatory层做了一层封装,但是目前还是beta版本)。

下面我们用闲鱼中的实际例子介绍下如何使用Observatory检查看Dart VM内存使用情况,注意所有关于性能的分析要在Profile模式下进行。

  1. 打开Observatory URL的Web页面。

    运行app,在控制台中查找类似输出日志listening on ws://127.0.0.1:64673/hXsWR_ZOsGk=/ws, 表示当前连接的VM地址,输入到浏览器就可以看到Observatory主界面,显示了dart vm一些基础信息,具体使用方法可以参考 官方文档,这里不再详细描述,我们重点关注右下角的allocation profile选项。

 
image
  1. 点击右下角allocation profile选项后,操作app进入想要分析的Flutter页操作,退出该页面,点击页面右上角 GC按钮触发手动GC,查看Class,发现有部分DX Class内存占用,这类class本应该只有在目标分析页会出现,退出目标分析也后手动GC会被完全释放,但是这里任然能看到相关内存占用,说明产生了内存泄漏。
 
image
  1. 点击对应class查看具体应用实例,点击对应实例进入查看引用路径,就能找到没有导致释放的引用变量,结合业务代码具体分析,就能发现泄漏的源头。
 
image
 
image

这里有一点需要注意,Observatory显示的Dart VM占用的内存信息要远远小于Android Profile/Xcode检测出的内存大小,因为存在部分只有系统工具能检测出的内存区块,例如一些完全不依赖于DartVM的skia对象,并且layer在engine中创建时并不能明确知道大小,所以采用虚拟近似值代替。

//engine/lib/ui/painting/engine_layer.cc
...
size_t EngineLayer::GetAllocationSize() {
  // Provide an approximation of the total memory impact of this object to the
  // Dart GC.  The ContainerLayer may hold references to a tree of other layers,
  // which in turn may contain Skia objects.
  return 3000;
};

下面我们总结了几种常见内存泄漏的场景,在Java中都可以一一对应找到类似的场景,大家在业务开发中注意避免

常见内存问题

  1. 未取消注册或回调导致内存泄露

示例代码:

class DownloadManager extends Object {
  ......
  abstract class DownloadListener {
    void completed(DXTemplateItem item);
    void failed(DXTemplateItem item, String errorInfo);
  }
  static List<DownloadListener> listenerList = List();
  static void downloadSingleTemplate(DXTemplateItem template, DownloadListener listener) async {
    listenerList.add(listener);
        ...
  }
...

修改方法:手动取消注册或回调

  // 移除
  static void removeDownloadListener(DownloadListener listener) {
    if (listener != null && listenerList != null && listenerList.contains(listener)) {
      listenerList.remove(listener);
    }
  }
  1. 资源未关闭或释放导致内存泄露,例如ImageStream的图片资源有没有被正常关闭导致的内存泄漏。

    问题代码:

void _resolveImage() {
    final ImageStream newStream =
    widget.image.resolve(createLocalImageConfiguration(context));
    assert(newStream != null);
    _updateSourceStream(newStream);
  }

修改方法:在图片组件被销毁时正确释放资源

@override
  void dispose() {
    ...
    _imageInfo.image.dispose();
    _imageInfo = null;

    super.dispose();
  }
  1. PlatformAssetBundle().loadString通过asset读取String内容会一直缓存读取的内容,造成内存无法释放

问题代码:

/// 通过asset读取Json
Future<Map<String, dynamic>> loadJsonAsset(String assetPath) async {
  _rootBundle ??= PlatformAssetBundle();
  final String jsonStr = await _rootBundle.loadString(assetPath);
  return json.decode(jsonStr);
}

修改方法:

/// 通过asset读取Json
Future<Map<String, dynamic>> loadJsonAsset(String assetPath) async {
  _rootBundle ??= PlatformAssetBundle();
  final String jsonStr = await _rootBundle.loadString(assetPath, cache: false);
  return json.decode(jsonStr);
}

PlatformAssetBundle继承于CachingAssetBundle,会在app整个生命周期中缓存读取的数据,如果不是需要频繁访问的话建议cache参数设置为false

 
image
  1. 另外很多同学有反馈过Flutter带图片的长列表滑动会造成内存一直上涨,flutter在1.17版本对这个问题做了优化,具体改动可以参考pr 14265

以上内容介绍了闲鱼在实践中遇到的Flutter内存问题解决思路,给出了内存泄漏定位方法。优化后能在一定程度上减小内存压力,避免不必要的内存占用。闲鱼在内存优化的方向上还有很多需要继续探索的地方,正在做的包括对图片库的缓存改造,layer层内存检测工具等等,朝着不断优化flutter性能体验努力。

posted @ 2020-08-23 16:03  小周同学、  阅读(402)  评论(0)    收藏  举报