Android Memory Optimizer (large rollup--on)

Source: Internet
Author: User

Reproduced please indicate this article from the Big Corn Blog (, thank you for your support!

Written in the front:

The idea of this paper mainly draws on the 2014-year Andevcon developer Conference of a lecture ppt, plus the online collection of various memory scattered knowledge points to summarize, select, simplified after finishing.

So I'm going to define this article as a tool class article, and if you're having a memory problem with Android, or you're going to be interviewing, or simply learning or reviewing memory-related knowledge, you're welcome to read. (At the end of this article I will try to list the articles I refer to).

Memory Introduction:RAM (random access memory). To be blunt is memory.

In general, Java involves the following areas in memory allocation:

Register (Registers): the fastest storage location because the register is inside the processor and we can't control it in the program

stack: a reference to the basic type of data and objects, but the object itself is not stored in the stack, but is stored in the heap

Heap: heap memory is used to hold objects and arrays created by new. The memory allocated in the heap is managed by the automatic garbage collector (GC) of the Java Virtual machine.

static field: A static storage area refers to the data that persists while the application is running in a fixed location, where Java specifically divides a static storage area in memory to manage some special data variables such as static data variables

Chang (Constant pool): The virtual machine must maintain a constant pool for each mounted type. A constant pool is an ordered set of constants used by that type, including direct constants (String,integer and floating point constants), and symbolic references to other types, fields, and methods.

non-RAM storage: Persistent storage space such as hard drives

Stack feature comparison:

For space reasons, here are just a few of the features of the stack.

Stack : When a variable is defined, Java allocates memory space for the variable in the stack, and when the variable exits the scope, Java automatically frees the memory space allocated for the variable, and the memory space can be immediately used for another.

Heap : When new in the heap generates arrays and objects beyond their scope, they are not freed and are not used until they are pointed to by a reference variable. Even so, the amount of memory is not released immediately, but is waiting to be taken away by the garbage collector. This is why the Java comparison accounts for memory.

stack : Access speed is faster than heap, second only to register. However, the disadvantage is that the size and lifetime of the data in the stack must be deterministic and inflexible.

Heap : The heap is a run-time data area that can be dynamically allocated memory size, so the access speed is slower. Because of this feature, the lifetime of the heap does not have to be told to the compiler beforehand, and the Java garbage collector automatically collects the data that is no longer used.

Stack : The data in the stack can be shared, and it is done by the compiler, which facilitates space saving.

For example: You need to define two variables int a = 3;int B = 3;

The compiler processes int a = 3 First, it creates a reference to a variable in the stack, and then finds out if there is a value of 3 in the stack, and if it does not, it stores the 3 in and then points a to 3. then the int b = 3 is processed, and after the reference variable of B is created, because there are already 3 values in the stack, B points directly to 3. In this case, A and B both point to 3. At this point, if you let a=4 again, then the compiler will re-search the stack for 4 values, if not, then store 4 in and let a point to 4; Therefore the change of a value does not affect the value of B.

Heap : For example, the modification of a in the upper stack does not affect B, whereas an object reference variable in the heap modifies the internal state of the object, which affects another object reference variable.

Memory consumption noun parsing:

VSS -Virtual Set Size Dummy memory consumption (contains memory occupied by shared library)

RSS -resident Set Size actually uses physical memory (contains memory consumed by shared libraries)

PSS -Proportional Set Size actual physical memory used (proportional allocation of memory consumed by shared libraries)

USS -Unique Set Size process consumes the physical memory alone (does not contain the memory occupied by the shared library)

In general, memory footprint has the following rules: VSS >= RSS >= PSS >= USS


Memory leaks can cause a lot of problems:

1. Slow response time (the JVM virtual opportunity triggers the GC frequently when memory consumption is high)

2. Inexplicable disappearance (when your program takes up more memory, it is more likely to get killed in the background.) Conversely, the smaller the memory footprint, the longer it will exist in the background)

3. Direct Crash (OutOfMemoryError)

Android memory facing problems:

1. Limited heap memory, original only 16M

2. Memory size consumption, etc. depending on the device, operating system level, screen size and different

3. The program cannot be controlled directly

4. Support background multitasking (multitasking)

5. Running on top of a virtual machine


This article mainly uses the following 5R method to optimize the Android memory:

1.Reckon (calculation)

The first thing you need to know about the memory consumed by your app is that you can Baizhanbudai

2.Reduce (Decrease)

Consume less resources

3.Reuse (Reuse)

When the first use is finished, try to use the other

5.Recycle (recycling)

Return a resource to a production flow

4.Review (check)

Review your program to see what is wrong with the design or code.

Reckon (calculation):

It is necessary to understand the memory usage of your application. If memory usage is too high, it needs to be optimized because less memory can reduce the chance that Android systems will terminate our process, and it can improve multitasking execution efficiency and experience.

Here are a few ways to view and calculate memory usage from the system memory (systems RAM) and heap memory (heap) Two:

System RAM (Systems Memory):

Observe and calculate the memory usage of the system, you can use Android to provide us with two tools procstats,meminfo. They have a memory usage that focuses on the background, and the other is memory usage at runtime.

Process stats:android 4.4 KitKat proposed a new system service called Procstats. It will help you better understand the memory usage of your app in the background (background). Procstats can monitor your app's behavior over time, including how long it's been running in the background and how much memory was used during that time. This helps you quickly find inefficient and irregular areas of your application to avoid affecting their performs, especially when running on low-memory devices. You can use the ADB shell command to procstats (adb shell Dumpsys procstats--hours 3), or the more convenient way to run the process Stats Developer Tools (Click Settings > Developer options > Process Stats on the 4.4 version of the phone) to see more details Meminfo:Android also provides a tool called Meminfo. It calculates the memory usage of each process according to the PSS standard (proportional Set size--actual physical memory) and sorts it by importance. You can do it via the command line: (adb shell Dumpsys meminfo) or use the device to click Settings > Apps > Running (unlike Procstats, which can also run on older versions) more about ProcstatsAnd MeninfoThe introduction can refer to an article I translated: Process Stats: Learn how your app uses memory

Heap Memory:

In the program you can use the following methods to query memory usage

Activitymanager#getmemoryclass ()

Query the limits of available heap memory

3.0 (honeycomb) above can request more heap memory by largeheap= "true" (though this counts as "cheating")

activitymanager#getmemoryinfo (activitymanager.memoryinfo)The resulting memoryinfo can be viewed in the following field properties: Availmem: Represents the system's remaining memory Lowmemory: It is a Boolean value, Indicates whether the system is running in low memory Hreshold: It represents low memory running when the system has less memory left

Android.os.debug#getmemoryinfo (Debug.memoryinfo memoryinfo)

The resulting memoryinfo can be viewed in the following field properties:

Dalvikprivatedirty:the private dirty pages used by Dalvik. Dalvikpss:the proportional set size for dalvik.dalvikSharedDirty:The GKFX dirty pages used by Dalvik.nativeprivatedirt Y:the private dirty pages used by the native heap.nativePss:The proportional set size for the native Heap.nativeshareddi Rty:the shared dirty pages used by the native Heap.otherPrivateDirty:The private dirty pages used by everything Else.oth Erpss:the proportional set size for everything Else.otherSharedDirty:The gkfx dirty pages used by everything else.

Dalvik: Refers to the memory used by the Dalvik. Native: Is the memory used by the native heap. It should refer to the memory allocated on the heap using c\c++. Other: Refers to memory used in addition to Dalvik and native. But what exactly does it mean? Include at least non-heap memory allocated in c\c++, such as memory allocated on the stack. Private: Refers to proprietary. Non-shared. Share: Refers to shared memory. PSS: Physical memory actually used (proportional allocation of memory occupied by shared libraries) Privatedirty: It refers to the size of the memory that is not shared and cannot be paged out (can is paged to disk). For example, the small object that Linux buffers in order to increase memory speed, even if your process ends, the memory will not be released, it just back into the buffer. Shareddirty: Referring to Privatedirty I think it should mean the size of the memory that is shared and cannot be paged out (can not be paged to disk). For example, the small object that Linux buffers in order to increase the allocated memory speed, even if all the processes that share it end, the memory is not released, it just goes back to the buffer.

Android.os.debug#getnativeheapsize ()

Returns the total memory size of the current process navtive heap itself

Android.os.debug#getnativeheapallocatedsize ()

Returns the amount of memory used in the current process navtive heap

Android.os.debug#getnativeheapfreesize ()

Returns the amount of memory already remaining in the current process navtive heap

Memory Analysis Tool (MAT):

Often memory leak analysis is considered a difficult task, typically performed by a team of experienced people. However, today we are going to introduce the MAT (Eclipse Memory Analyzer) is considered to be a "fool-like" Heap Dump file analysis tool, you only need a click of the mouse to generate a professional analysis report.

Such as:

For detailed mat use I recommend this article: Heap dump file analysis using Eclipse Memory Analyzer

Written at the end:

I'm going to divide the article into top, middle, and bottom three parts. The remaining Reduce,reuse,recycle,review will be summarized in the next two articles.

Reduce,reuse See the second article:

Because the memory knowledge is very fragmented, and I am now learning to sell, so in order to collect more information as much as possible and ensure that the accuracy of the content update speed may be slow. Because there's something else in the middle that sucks seven or eight bad.

The purpose of writing this article is to make a large summary, the scattered memory knowledge points summed up, if there are errors, deficiencies or suggestions want to tell me.

Reference article:

Andevcon Developer conference Speech ppt:putting Your App on a Memory Diet

Deep Java core Java memory allocation principle explaining (

Process stats:understanding how Your App Uses RAM ( 38390135) How to view memory in Android (

Android Memory performance optimization (internal data Summary) (

Android Memory Optimizer (large rollup--on)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.