Android---memory performance optimization

memory thrashing

  \bullet Memory jitter is caused by a large number of objects entering and exiting the nascent area in a short period of time . The memory fluctuates from high to low, with a tendency to rise and fall rapidly in a short period of time, and the analysis graph is jagged .

  \bullet It is accompanied by frequent GC, which will occupy a large amount of UI thread and CPU resources, which will cause the overall app to freeze (because the GC will stop the working thread when reclaiming memory), and even the possibility of OOM (reason: create a large number of objects in the new generation , and the space allocated to the new generation is relatively small, so it will occupy part of the space of the old generation . If there is no continuous space allocated to this large object, an OOM error will be reported at this time).

memory leak

  \bulletThe heap memory  that has been dynamically allocated in the program is not released or cannot be released by the program for some reason , resulting in a waste of system memory.

Judging the survival of the object --- reachability analysis

If an object is root-reachable , it will not be collected; if it is root-unreachable , it will be collected.  The memory leak is that an object satisfies the root reachability, but it is not available.

A typical case of memory leak : a static variable refers to an Activity, and this static variable is global, as long as the APP process is not killed, this static variable will always exist. And the Activity has executed the life cycle onDestory(), but the Activity is applied by the static variable and the root is reachable, then the Activity has a memory leak.

Memory Analysis Tool

1. Android Profiler

The Memory Profiler is a component in the Android Profiler that helps us identify memory leaks and memory thrashing that can cause apps to freeze or even crash. It displays a real-time graph of the application's memory usage, allowing us to

  \bullet capture heap dump

  \bullet enforce garbage collection

  \bullet track memory allocation

2. MAT(Memory Analyzer Tool)

For comparison of memory snapshots, in order to find out the objects of memory leaks more efficiently, two heap dump files are generally obtained (dump one first, and then dump another after a while). The comparison results can be easily located.

Optimization case

String splicing will create a new string object every time, so use StringBuilder to complete it as much as possible. StringBuilder internally operates a character array to complete.

Guess you like

Origin blog.csdn.net/qq_44950283/article/details/130092318