Android Memory performance optimization (internal data summary) go

Source: Internet
Author: User

Just the introduction of children's shoes Ken can have a question, Java is not a virtual machine, memory will be automated management, we do not have to manually release resources, anyway the system will be done to us. In fact, there is no concept of pointers in Java, but the use of pointers still exist, blindly rely on the system of GC, it is easy to create a waste of memory.

Java garbage collection based memory mechanism

Java's memory management mechanism automatically reclaims memory consumed by useless objects, easing the burden of manually managing memory

1: From the application, use, release need manual management

2. Java: Memory of useless objects is automatically recycled

What kind of object is a useless object

1. Java uses a reference to manipulate a specific object, referencing a pointer similar to C. An object can hold references to other objects.

2. Start with a set of root objects (GC Roots), traverse all objects by the reference relationship before the object, and mark all the objects that can be reached during the traversal. If an object is not unreachable by the root object, it is garbage collected.

What are the GCRoot?

1. Class: Classes objects loaded by the system's ClassLoader

2. Static fields

3. Thread: Alive Thread

4. The local variables or parameters of the Stack Local:java method

5. Local references in JNI Local:jni methods

6. JNI Global: JNI Reference globally

7. Monitor used: monitoring object for synchronization

8. Help by VM: Objects reserved by GC for special purposes of the JVM

Memory leaks in Java programs

The object's memory cannot be reclaimed by the program's execution logic after it has been allocated, and cannot be recycled by the object's memory

Damage to memory leaks

1, causing OutOfMemoryError

2, high memory consumption, JVM virtual opportunity to trigger GC frequently, affecting program response speed

3, the memory consumption of the program is easy to be a variety of cleanup optimizer aborted, users are more inclined to uninstall these programs

Android apps are developed in Java, and the maximum available heap memory for each application is limited by the Android system

Limited heap memory size for Android per app

1, the usual situation is 16m-48m

2. Query available heap memory limits via Activitymanager's Getmemoryclass ()

3, 3.0 (Honeycomb) More than the version can be largeheap= "true" to request more heap memory

Nexus S (4.2.1): normal 192, Largeheap 512

4. OutOfMemoryError () will be thrown if the memory you are trying to request is larger than the current remaining heap memory

5, the application due to various limitations, need to pay attention to reduce memory consumption, to avoid memory leaks.

Use the Mat tool to detect memory leaks

Creating a new memory analysis in the Attempt window will show a

No, you can go to http://www.eclipse.org/mat/downloads.php and install the mat.

Under Android's debug environment Ddms, locate the heap dump

Dump the current in-memory image file, *****.hprof

Can clearly see each part take up the memory size.

You can also switch attempts, group to see the details of different classes of different packages.

Heap Dump

? Contains a memory snapshot of the Java process that triggered the heap dump generation, with the main content being allocated in heap memory for each Java class and object

Memory Analyzer Tool (MAT)

Common causes of memory leaks

Context Object leak

1. If a class holds a strong reference to a context object, it needs to check if its lifetime is longer than the context object. Otherwise, a context leak may occur.

2. View holds a reference to the context object in which it was created, which can cause a memory leak if the view object is passed to a strong reference that has a longer lifetime than the view context.

For example, a memory leak for view#settag (int, Object) https://code.google.com/p/android/issues/detail?id=18273

3. Assign the context object to the static variable.

Avoid context object leaks checklist

1. Check that all objects holding strong references to the context object have a life cycle beyond the context object that they hold.

2, check whether the view out of the context of the view outside the place, if there are words need to check the life cycle.

3, it is best not to have the context member variable in the tool class, try to pass in the call parameter directly when calling the function. If you must have a context member variable, you might consider using WeakReference to refer to the context object.

4. View holds a reference to the context object in which it was created, which can cause a memory leak if the view object is passed to a strong reference that has a longer lifetime than the view context.

5, check the context or view object assigned to the static variable place, see if there is a context leak.

6. Check all places where the view is placed in the container class (especially the static container class) to see if there is a memory leak. 7, the use of Weakhashmap also need to pay attention to there is no value-key reference.

7, try to use ApplicationContext.

Handler Object leaks

1, the message sent to handler is actually added to the main thread of the queue waiting for processing, each message holds its target handler strong reference.

As we usually use the anonymous inner class handler

?
123456 <span style="font-size:18px;">HandlermHandler = newHandler() {    @Override    publicvoidhandleMessage(Message msg) {       mImageView.setImageBitmap(mBitmap);    }}</span>



The above is a simple use of handler. When using an inner class (including an anonymous class) to create a handler, the handler object implicitly holds a reference to an external class object (usually an activity) because view is attached to an activity. Handler usually comes along with a time-consuming background thread (for example, pulling pictures from the web), which notifies handler via a message mechanism after the task has finished executing (the sample is downloaded), and then handler updates the image to the interface. However, if the user shuts down the activity during a network request, and normally the activity is no longer used, it may be reclaimed during GC checking, but since the thread has not finished executing, the thread holds the handler reference (otherwise how does it send a message to handler?). This handler also holds the activity reference, causing the activity to not be recycled (i.e. memory leaks) until the end of the network request (the sample download is complete). Also, if you execute the handler postdelayed () method, the method will load your handler into a message and push the message into the MessageQueue, before the delay you set arrives, There will be a chain of activity, MessageQueue, message, Handler, which causes your activity to be referenced and not recycled.

Of course, for the reason that handler holds references externally, we can set the activity to a weak reference and, when unnecessary, no longer execute the internal method.

?
1234567891011121314151617181920212223242526272829303132 <span style="font-size:18px;">/** * @author zhoushengtao * @since 2013-12-16 下午3:25:36 */ import android.app.Activity;importandroid.content.Context;importandroid.os.Handler;importandroid.os.Message; importjava.lang.ref.WeakReference; publicclass WeakRefHandler extends Handler{    WeakReference<context> mWeakContext;     public WeakRefHandler(Context context)    {        mWeakContext = newWeakReference<context>(context);    }     @Override    public void handleMessage(Message msg)    {        if((mWeakContext.get() instanceofActivity )&& ((Activity)mWeakContext.get()).isFinishing())                return ;        if(mWeakContext==null){            return ;        }        super.handleMessage(msg);    }}</context></context></span>



2. Non-staticinner class and anonymous class hold a reference to their outer class.

Memory leaks due to drawable.callback

The Drawable object holds a reference to the Drawable.callback. When a Drawable object is set to a view, the Drawable object holds a reference to the view as a drawable.callback

Avoid drawable.callback causing memory leaks

? Try not to save the Drawable object in the static member

? For drawable objects that need to be saved, call Drawable#setcallback (null) when needed.

Other memory leaks < yo? " http://www.2cto.com/kf/ware/vc/"target=" _blank "class=" Keylink ">vc3ryb25npjwvcd4kphagywxpz249" left "> 1, Memory leaks caused by Android DigitalClock http://code.google.com/p/android/issues/detail?id=17015

2. When using the Map container class, the class as key does not implement the hashcode and equal functions correctly

Other memory leaks

? Memory leaks in JNI programs

1, Malloc/free.

2. JNI Global Reference

? Thread-local Variable

1, equivalent to the thread object member variable, can store the threads related state

2. If thread is a alive state, then the object in thread-local cannot be GC.

Process Memory footprint Monitoring Tool

Dumpsys

? $ Dumpsys meminfo [PID]

Procrank + Shell Script

? #procrank

1. vss-virtual Set Size Virtual memory consumption (contains memory occupied by shared library)

2. Rss-resident Set Size actually uses physical memory (contains memory occupied by shared library)

3. pss-proportional Set Size actual physical memory used (proportional allocation of memory occupied by shared libraries)

4. Uss-unique the Set Size process consumes the physical memory alone (does not contain the memory occupied by the shared library)

Shell Script

#!/bin/bash

While true; Do

Adbshell Procrank "grep" Com.qihoo360.mobilesafe "

Sleep1

Done

Of course, some models of SH are through the third-party mobile phone business streamlined, a lot of commands are not used. Procrank is a command that is often streamlined.

In view of this:

Wrote a gadget to detect real-time changes in memory,

GitHub Address: Https://github.com/stchou/JasonTest

Summary

1. Think twice before you save the object

I. The object itself has no implied references

II. When to recover after saving

2. To understand common implicit references

I. Anonymous class outer class

II. View to Context

3. To check if memory consumption is abnormal through various tools

4. When creating a large object, check its life cycle

/**
* @author Zhoushengtao (Zhou San)
* @since May 21, 2014 6:18:29

Android Memory performance optimization (internal data summary) go

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.