Keeping a reference to a View in a Fragment causes memory leaks?

后端 未结 6 1093
难免孤独
难免孤独 2021-02-04 13:30

Somebody told me the following, but I am a bit perplexed.

Please, would you be able to confirm or dispute it?

(the Fragment is

6条回答
  •  梦毁少年i
    2021-02-04 14:04

    Disclaimer:

    I will post another answer because I think I couldn't extract the exact use case from the question in the first read. I am waiting for the approval of the edit request I made to this question to know I understood the question properly. I am keeping this answer because I believe there are some useful tips and links that might help someone. On the other hand, in certain cases my answer is right.

    Keeping a reference to a View in a Fragment causes memory leaks?

    ABSOLUTELY NOT since the field is declared private, no object from outside of the Fragment i.e. Activity can access a hard reference of it from the Fragment object. Therefore, it will not prevent the Fragment object from being garbage collected.

    You might ask, will it cause memory leak when I use this reference in an async callback?

    My answer would be, yes it will cause memory leak for keeping reference inside the async callback but not due to keeping its reference in the Fragment. However, this memory leak will also happen even if you don't store the View reference in the Fragment.

    In general, to avoid memory leak, you should watch out the following simple patterns,

    1. Never reference views inside Async callbacks
    2. Never reference views from static objects
    3. Avoid storing views in a collection that stores values as hard references

    This official video, DO NOT LEAK VIEWS (Android Performance Patterns Season 3 ep6) will help you understand it better.

提交回复
热议问题