Android Memory Optimizer (large rollup--on)

Source: Internet
Author: User

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 (statics field): a static storage area is the data that persists while the application is running at a fixed location, and 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


OOM:


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


5R:

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)

Back to resources

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 in the 4.4 version of the phone)
Click on a single entry to view more information
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 execute it from the command line: (adb shell Dumpsys meminfo) or use the device to click Settings > Apps > Running (unlike Procstats, it can also run on older versions)
For more information on procstats and Meninfo , 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 that indicates whether the system is in a low memory run Hreshold: It represents a low memory run 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 : Theproportional set size for Dalvik. dalvikshareddirty : Theshared dirty pages used by Dalvik. nativeprivatedirty : Theprivate dirty pages used by the native heap. NATIVEPSS : Theproportional set size for the native heap. nativeshareddirty : Theshared dirty pages used by the native heap. otherprivatedirty : Theprivate dirty pages used by everything else. OTHERPSS : Theproportional set size for everything else. othershareddirty : Theshared 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: physically used physical memory (proportional allocation of memory consumed by shared libraries) Privatedirty: It refers to the size of the memory that is unshared and cannot be paged out (can not bepaged 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 bepaged 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. Now it's all done:

Memory Introduction, Recoken (calculation) See :android Memory Optimizer (large rollup--on)

reduce (decrease), reuse (reuse) See :Android Memory Optimizer (large rollup--medium)

Recycle (recycling), Review (check) See :android Memory Optimizer (big summary-full)


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 (http://developer.51cto.com/art/201009/225071.htm)

Process stats:understanding how Your App Uses RAM (http://blog.csdn.net/a396901990/article/details/38390135) How to view memory in Android (http://blog.csdn.net/hudashi/article/details/7050897)

Android Memory performance optimization (internal data Summary) (http://www.2cto.com/kf/201405/303276.html)

Android Memory Optimizer (large rollup--on)

Related Article

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: info-contact@alibabacloud.com 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.