android APP performance optimization memory optimization

APP memory optimization method

1. Data structure optimization

2. Object reuse

3. Avoid memory leaks

Data structure optimization

1. Frequent use of string splicing do not use the "+" method, you should use StringBuilder, the "+" method will generate useless intermediate variables, and it is difficult to delete

2. ArrayMap and SparseArray replace HashMap

HashMap has low efficiency and high memory usage. Using the first two can solve this problem. An entry in HashMap requires an additional 32B

3. Memory jitter

length=200000;


Because the length is relatively large, each time a new String[length] takes up a relatively large space of the new generation, it is very likely that the space of the new generation is full at this time, so Minor GC will be performed (other threads are stopped at this time) , and this time it appears multiple times. APP operation efficiency is reduced.

How to solve?

Just put the above line directly outside the loop.


Such a memory saw graph can be seen in android Monitor

object reuse

1. Reuse the resources that come with the system

For example, using Application Context instead of Activity Context (mentioned later)

2. ConvertView reuse of ListView/GridView

3. Avoid the creation of objects in the onDraw method

memory leak

Memory leak: Due to code flaws, although this memory is stopped, it is still occupied by other things, making it impossible for GC to reclaim it.



Open the Activity of this thread, then exit, and then open it again. After exiting and repeating the operation, you will find that this activity occupies more and more memory.




Repeatedly, and after clicking GC, you will find that the data of 110 has been getting bigger.

Why? When we close this activity, because this thread sleeps for 5 minutes, it will still exist after it is closed, and the system has no way to recycle it. When the activity is opened again, the above activity will become the culprit of the memory leak.

As can be seen from the above, Activity is prone to leaks

So for programs, use Application Context instead of Activity Context.

One more thing. Pay attention to whether the Cursor object is closed in time. If it is not closed, it is prone to memory leaks.

Guess you like

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