Memory management of Android development

Source: Internet
Author: User

Concept

Application development is inseparable from storage, storage is divided into network, memory, sdcard file storage and external SDCard2 file storage, development must pay attention to memory management to avoid oom, lag and other bad user experience, but also pay attention to the variable recovery, to avoid memory leaks. Here's a look at some basic terminology related to the subject.

    • RAM (random access memory) memory

    • 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

Comparison of the characteristics of stacks

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.

If you're not clear enough about the stack, take a look at the following figure

A memory leak, also known as a "storage leak", is a dynamically opened space with dynamic storage allocation functions that is not released after use (the value stored by the stack's storage space), resulting in the deposit element being occupied. Until the end of the program. (In fact, the memory space is not recycled after use) is called memory leaks

Memory Analysis

How do we know if there is a memory leak that requires a memory analysis tool mat, or an open source project Leakcanary, first of all, we'll go to the official website to find out about the use of mat and get an overview to practice.

First of all we need to install mat, if you are eclipse development has not turned to Android Studio, then only need to install the MA plug-in, see (Latest Address: http://download.eclipse.org/mat/1.5/update-site/).

Of course you use Android Studio, but do not want to use Eclipse to analyze, then you can download the independent mat, extract the effect, double-click Run to open.

Build a test Java program within the ①eclipse development tool and test the code as follows

import java.util.ArrayList;import java.util.List;publicclass Main {/**   * @param args   */  publicstaticvoidmain(String[] args) {    new ArrayList<String>();    while (1<2){      list.add("OutOfMemoryError soon");    }  

Running will burst the memory leak problem

ExceptioninchThread"Main"Java. Lang. OutOfMemoryError: Java heap space at Java. Util. Arrays. CopyOf(Unknown Source) at Java. Util. Arrays. CopyOf(Unknown Source) at Java. Util. ArrayList. Grow(Unknown Source) at Java. Util. ArrayList. Ensureexplicitcapacity(Unknown Source) at Java. Util. ArrayList. Ensurecapacityinternal(Unknown Source) at Java. Util. ArrayList. Add(Unknown Source) at Test. Main. Main(Main. Java: -)

generate Xx.hprof file, using mat for analysis, there are two scenarios for generating xx.hprof files, the Java project under Eclipse has run as >run config as an example (another mentioned later)

Add VM arguments and configure output xx.hprof file directory, run the above error, open Directory to see Xx.hprof file

Is it a swollen thing when you think that you are about to succeed when you are filled with joy and suddenly give you a whole place?

The reason: The Android virtual machine exported the memory file Hprof file format is not the same as the standard Java hprof file format standard, the root cause of the virtual machine inconsistency between the two. Only need to use the SDK's own conversion tool to convert it, hprof-conv source file destination file in the way to find a solution to this problem, encountered a large B-pit, http://blog.csdn.net/pugongying1988/article/ details/9122699 This blog tells me in the Tools tool directory, I command line how can not find the program, I suspect is not I did not install plug-ins, reload after the plugin or not, after several toss here to find it

Bright Blind This is the tools directory, immediately steeds, straight call!! Back to the chase, switch to this directory to re-export the Xx.hprof file with the Hprof-conv command (for convenience, the old and new xx.hprof files are placed in the directory)

The deal is not a version of the problem (not absolute), after several verification, special is the Eclipse Export version issue (run as config export version of the issue, the specific reason did not delve into), Finally, the Xx.hprof file exported via DDMS is no problem (Supplemental Note: The original blog determines whether the version of the issue is correct, we use the Android Studio development, through the DDMS export that really is not a version of the problem, through the above command is OK)

    • Histogram
      lists the collection of object instances, shallow size and retained size for each type of instance collection. Shallow size refers to the amount of memory consumed by an object, such as 4 bytes per object, or 8 bytes, depending on your operating system (32-bit, or 64-bit), the concept of retained size relies on the concept of retained set, retained set refers to the collection of objects that are removed by the garbage collector when object X is recycled, and retained size is retained The amount of memory the set is holding.

To do this, enter the Overrview view below

Filter the list after the rules, followed by

Through path to GC Root (the object held by the JVM, such as the currently running thread object, the object loaded by Systemclass loader is called the GC Roots, the reference chain from an object to the GC Roots is called path to GC Roots, by analyzing p Ath to GC roots can find out the memory leak problem in Java, when the program is not accessing the object, it still exists to the reference path of the object. The exact location where the tracking variable is not recycled

According to the xx.hprof file tracking that provides the demo, the homeactivity inside calls the Drawablehelper class, the internal mcontext variable causes the memory leak, here the Mcontext variable is as follows (because the internal other methods set properties require the context object, it should be passed Into the constructor method, the private does not static property, but the different activity calls will cause the context object problem, So it is best to pass in the context object as Activity.getapplicationcontext, or other today's attribute method passed in the parameter, so drawableheper do not save the context instance reference, This analysis let me understand a bit: not when all are suitable for single-case mode, to specific problems specific analysis)

 Public classDrawablehelper {protected StaticDrawablehelper Mdrawablehelper;protected StaticContext Mcontext;Private Drawablehelper() {    } Public StaticDrawablehelpergetinstance(Context context) {if(Mdrawablehelper = =NULL) {synchronized (Drawablehelper.class) {if(Mdrawablehelper = =NULL) {Mdrawablehelper =NewDrawablehelper (); }}} Mcontext = context;returnMdrawablehelper; }
memory-Optimized features

① repeating strings is a typical example of memory waste: Multiple character arrays have the same content. The contents of a character array usually give the idea of how to reduce repetition.

② Empty collection space does not store any data. If only a few collections hold the data, consider lazy initialization, which is to create the collection only when needed.

③ collections are typically created with a default initial capacity. A collection of many low fill rates indicates that the initial capacity can be reduced.

④ Soft Reference Static resources

⑤ uses data containers that have been optimized in the Andorid framework, such as Sparsearray,sparsebooleanarray and Longsparsearray. Containers similar to HASHMAP are not very efficient, because in each MAP each time the data is stored, he needs to separate a separate Entry object for the transfer of Fang. Sparsearray is more efficient because it prohibits the system from automatically encapsulating key-value pairs. And you don't have to worry about losing the original information (Abslistview control record checked properties and position)

⑥ avoiding the Dependency injection framework, using a dependency injection framework similar to the Xutils viewutils annotation module, may make your code more beautiful, because they can reduce the code you need to write and provide an adaptive environment for testing or for other conditions to change. However, these frameworks, when initialized, consume a lot of work to scan your code because of annotations, which will allow your code to spend more resources on memory mapping. While these memory can be recycled by Android, it takes a long time to wait for the entire paging to be released.

⑦ uses the obfuscation proguard to remove unnecessary code.

⑧ do not use a large-volume class library for a particular requirement, such as a round head that requires only a circle head, and no need to use the open source Photoview library, a relatively lightweight circleimageview with the appropriate or custom cropping controls.

⑨ constants are modified with static final, (context does not use static modification, it is easy to cause memory leaks)

⑩ variables that are not used, even if NULL is released

third-party library leakcanary Practice

Address: Https://github.com/square/leakcanary
Project Dependencies

{   debugCompile ‘com.squareup.leakcanary:leakcanary-android:1.4-beta2‘   releaseCompile ‘com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2‘   testCompile ‘com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2‘ }

Application Initializing Libraries

LeakCanary.install(this);

After running if the program has a memory leak, will be prompted to find the leaks icon open can see the leak location, analysis of the reasons, while we can also share heap dump, share. hprof files to the computer, detailed positioning analysis through the mat. (. hprof file comparison big recommended WiFi transfer)

Summary

Patchwork still completed this blog,leakcanary integration into the project to help us analyze the location of leaks, if not clearly analyzed for specific reasons, can be everywhere. hprof file through Mat analysis, and finally a brief summary for individuals:

① after development must pay attention to the use of single-case mode, too many instance, not all classes are required.

②static modifier constants are changed to static final (individual cannot final attempt to remove static adornments)

③context and activity should not be modified with static

④ memory leaks: Open up the stack's storage reference management, kill the non-surviving stack references, and release them in a timely manner.

References

http://blog.csdn.net/a396901990/article/details/37914465
Http://www.jianshu.com/p/c49f778e7acf
http://blog.csdn.net/pugongying1988/article/details/9122699
Http://wiki.eclipse.org/MemoryAnalyzer#HPROF_dumps_from_Sun_Virtual_Machines
http://blog.csdn.net/xu_fu/article/details/45678373
http://blog.csdn.net/tiantangrenjian/article/details/39182293

Featured Blogs

http://blog.csdn.net/a396901990/article/details/38904543
http://blog.csdn.net/a396901990/article/details/38707007

Memory management of Android development

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.