SDWebImage下载高清图内存问题
原文地址 http://www.jianshu.com/p/1c9de8dea3ea
图中可以看出,内存暴增的罪魁祸首是YYImage,再进一步定位问题,如图:
instrument分析图:
我又疑惑了,既然是为了优化,为啥会适得其反呢?我百思不得其解,最后在SDWebImage的issues找到了相关的讨论: https://github.com/rs/SDWebImage/issues/538 其中一个harishkashyap大神是这么回答的:
harishkashyap commented on Dec 23, 2014 Its the memory issue again. decodedImageWithImage takes up huge memory and causes the app to crash. I have added an option to put this off in the library but defaulting to YES so there aren't any breaking changes. If you put off the decodeImageWithImage method in both image cache and image downloader then you shouldn't be seeing the VM: CG Raster data on the top consuming lots of memory
decodeImageWithImage is supposed to decompress images and cache them so the loading on tableviews/collectionviews become better. However, with large set of images being loaded, the experience worsened and the memory of uncompressed images even with thumbnails can consume GBs of memory. Putting this off only improved performance.
https://github.com/harishkashyap/SDWebImage/tree/fix-memory-issues
这位大神提到,decodeImageWithImage这个方法用于对图片进行解压缩并且缓存起来,以保证tableviews/collectionviews 交互更加流畅,但是如果是加载高分辨率图片的话,会适得其反,有可能造成上G的内存消耗。该大神建议,对于高分辨率的图片,应该禁止解压缩操作,相关的代码处理为:
解压缩操作中,每一个像素点都会分配一个空间来存储相关值,那么分辨率越高的图片,就意味着更多数量的像素点,也就意味着需要分配更多的空间!所以对于高分辨率图来说,解压缩操作的确会造成内存飙升,即使是几M的图片,解压缩过程中也是有可能消耗上G的内存! 既然如此,我决定按照harishkashyap大神的方法,直接让下载高分辨率图的地方,禁止解压缩操作! 项目中,高清图涉及到的地方,都全部已经封装起来了,那么就轻松了很多。为了保证封装类不对外界产生影响,我只在调用封装类时,禁用解压缩,调用完毕再恢复原设置即可。这样既能保证高分辨率图不crash,也能保证其他地方,普通图片依旧可以通过解压缩进行优化。
当然,你也可以设置SDWebImage的其他参数,比如是否缓存到内存以及内存缓存最高限制等,来保证内存安全:
号外:苹果官方给出了一个下载高清大图的demo,内存消耗很低。感兴趣的朋友也可以看看: https://developer.apple.com/library/ios/samplecode/LargeImageDownsizing/Introduction/Intro.html
Last updated