memory optimization strategy

introduction


After the home page function is completed, it will occasionally crash when using it, and I have a look at the oom log.

Think carefully about the current layout structure will indeed have such a problem

Only the ViewPager in the Fragment of the home page contains 21 sub-Fragments

Each sub-Fragment contains multiple views and each view has a loaded image. How to describe it as scary?

There are 100 direct child views of Fragment, which are returned by the interface. And the child view may be a ViewGroup that wraps the view.

The android profiler shows that the memory exceeds 400M, and the picture accounts for nearly 200M. The memory optimization needs to be solved urgently.

text


Let's talk about the original first:

I mentioned before that the homepage ViewPager has nearly 10 caches (I only set 3), there is no lag or oom when sliding the content, and the loading of images is also very smooth.

One small detail caught my attention, when the Fragment slides to the bottom and then slides to the top, the loading effect of the image is faded. Obviously did some tricks, mark it first, as for what it is, I haven't figured it out yet.

optimization

1. Fragment
onCreateView will inflate a View each time, and more Fragments will inflate when switching back and forth.

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_content, container, false)
        }

There will be multiple images in each Fragment, so the memory usage is cleared when onDestroyView

        Glide.get(context).clearMemory()
        System.gc()

2. ViewPager
sets the number of caches for ViewPager

        viewPager.offscreenPageLimit=3

3. Picture format All pictures
previously operated by Glide are ARGB_8888. One pixel in this format will occupy 32 bits and 4 bytes. Now it is changed to the smallest RGB_565, which occupies 16 bits and 2 bytes, which is doubled.

4. Glide
is set to only save, modified pictures

                    .diskCacheStrategy(DiskCacheStrategy.RESULT)

5. Do not load pictures when sliding Set a sliding monitor
for RecyclerView, and load pictures when the state of RecyclerView is SCROLL_STATE_IDLE

Through the above operation, the picture occupies a maximum memory of 130M and there is no oom. I always feel that there is something missing. Mark these first and then continue.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325994395&siteId=291194637