android:largeHeap=“true” convention?

后端 未结 2 1462
Happy的楠姐
Happy的楠姐 2020-12-09 10:06

I\'m writing an image gallery app and I keep running into out of memory errors. I cache all my images but the problem occurs when I try switching between images real

2条回答
  •  -上瘾入骨i
    2020-12-09 10:29

    First, make sure you aren't loading larger bitmaps than necessary:
    Load a Scaled Down Version into Memory.


    Then, before trying largeHeap, try to free the memory quickly yourself:

    If you call bitmap.recycle(); as soon as you are SURE you will not use a bitmap again, then the bulk of that bitmap's memory will be immediately freed. (When the GC gets around to it, all that remains is a tiny object.)


    On newer Android versions, there are alternatives (instead of recycle) that may be more effective:
    Managing Bitmap Memory

    Personally, I still use recycle often, especially if I might be loading a different size image, so can't reuse the existing one. Also, I find it easier to code "unloading" of old media separately from "loading" of new media, when changing to a different fragment or activity:
    As leave the old fragment, all old bitmaps I recycle (then, if reachable from a static field, set to null).


    The rule of thumb for whether to use largeHeap, is to consider it after you've tried alternative ways to reduce memory usage.

    Code your app so you could turn it off again, and still run.

    For example, monitor your memory usage, and load "scaled down" bitmaps if memory is tight. Will the user really notice if a given image is not at their device's "retina" resolution?

    Or if it is an older, slower, device, will largeHeap make your app feel unresponsive / jerky? If so, can you drop resolution even further, or show fewer bitmaps at one time?

    Get your app to work in all circumstances, without largeHeap [by techniques mentioned above]. NOTE: you can "force-test" running on tight memory, by allocating some "dummy" bitmaps, and hold references to them in global fields, so they don't get freed.

    NOW you are able to evaluate the trade-off, as it affects YOUR app:

    When you do turn largeHeap on, use your app heavily - are there places where it is now "more sluggish", or animations "stutter" or otherwise seem less smooth? BE SURE TO TEST ON AT LEAST ONE OLDER DEVICE, AND ON ONE HIGH_RESOLUTION DEVICE. You might be seeing long GC times, due to the larger heap.

    OR you might conclude that largeHeap is working well for you, and now you can confidently say that it is the best choice in your circumstance.

提交回复
热议问题