Memory Analysis of Android applications

Source: Internet
Author: User

Original article connection: Click to open the link. The translation is as follows:

Dalvik virtual opportunity for garbage collection, but this does not mean that you can ignore memory management, instead, you should pay more attention to memory usage on mobile devices with limited memory. In this article, let's take a look at several memory analysis tools in the android SDK. These tools can help you track the memory usage in your application.

Some memory usage problems are obvious. For example, if the application exposes the memory every time the user touches the screen, it may eventually triggerOutOfMemoryErrorErrors and application crashes. Some problems are subtle, but may only reduce the performance of applications (because frequent garbage collection takes a long time) or the entire system.

Commercial tools

The android SDK provides two main methods for analyzing the memory usage of applications:Allocation TrackerTag and heap dump ).Allocation TrackerIt is used to obtain various memory allocations occurring in a given period of time, but it cannot provide the overall information of the application heap. AboutAllocation TrackerFor more information, see the article tracking.
Memory allocations (translation connection: Click to open the link ). The rest of this article focuses on heap, a more powerful memory analysis tool.

Heap is a snapshot of the application memory usage. It is stored in a binary format named hprof. The format used by the Dalvik virtual machine is similar but not identical to that in the Java hprof tool. There are multiple ways to generate heap for running applications, one of which is to use ddmsDump hprof FileButton. For more detailed heap conversion information, you can useandroid.os.Debug.dumpHprofData()Function creates a stack to obtain the program.

For analysis heap, you can use standard tools such as jhat or eclipse mat. However, we first need to convert the. hprof file generated by Dalvik to the hprof format supported by j2se. You can usehprof-convTool to achieve this conversion, for example:

hprof-conv dump.hprof converted-dump.hprof

Instance: Debugging Memory leakage

In the Dalvik image, the programmer does not need to display the allocation and release of memory, so it is not as well as in C and C ++ (because the allocation and release of memory are not handled properly) memory leakage only occurs when you reference an object that is no longer needed. Sometimes a single reference makes it difficult to recycle a large number of objects (Note: The reference to activity context in the article translated by the former to prevent memory leakage belongs to this example ).

Let's take the honeycombgallery In the android SDK (the example is in $ SDK/samples/Android-11/honeycombgallery) as an example. This example is just a simple photo gallery application, demonstrate how to use some new APIs of honeycomb. (To compile and download the sample code, see instructions ). Here we intentionally add Memory Leak Code to the application to demonstrate how to debug Memory leakage.

Suppose we want to modify the program to obtain the display image from the network. To make the response more responsive, we may implement a cache for storing recently browsed images, which can be achieved by making minor changes to contentfragment. java. Add a static variable at the top of the class file:

private static HashMap<String,Bitmap> sBitmapCache = new HashMap<String,Bitmap>();

This is the cache of the bitmap to be loaded. ModifyupdateContentAndRecycleBitmap()Method to check the cache before loading, and then add the image to the cache.

void updateContentAndRecycleBitmap(int category, int position) {    if (mCurrentActionMode != null) {        mCurrentActionMode.finish();    }     // Get the bitmap that needs to be drawn and update the ImageView.     // Check if the Bitmap is already in the cache    String bitmapId = "" + category + "." + position;    mBitmap = sBitmapCache.get(bitmapId);     if (mBitmap == null) {        // It's not in the cache, so load the Bitmap and add it to the cache.        // DANGER! We add items to this cache without ever removing any.        mBitmap = Directory.getCategory(category).getEntry(position)                .getBitmap(getResources());        sBitmapCache.put(bitmapId, mBitmap);    }    ((ImageView) getView().findViewById(R.id.image)).setImageBitmap(mBitmap);}

Here, we intentionally introduce Memory leakage: only adding images to the cache but never removing them. In reality, we may use some measures to limit the cache size.

Use ddms to detect heap usage

Ddms (Dalvik debug monitor server) is one of the main debugging tools for Android and part of the eclipse ADT (Android debug tools) plug-in. You can find its independent version in the tools/directory of the android SDK. For more information about ddms, see using ddms.

Let's use ddms to check the usage of the above application heap. One of the following two methods can be used to start ddms:

1) Use Eclipse: ClickWindow> open perspective> other...> ddms

2) run the following command in the tools/directory:ddms(InRun the command on MAC/Linux./ddms)

Select a process in the left-side window of eclipsecom.example.android.hcgalleryAnd clickShow heap updatesSwitch toVM heapTags (blogger note: the tags and button names in different versions may be different. My eclipse version is Helios, the button name on the toolbar is update heap, And the label name in ddms is heap, however, no matter what the name is, the function and position are the same ). The VM will be updated after each garbage collection.
Some basic statistics about heap memory usage displayed in heap. If you want to see the first update, clickCause GCButton.

We can see that the program allocation (AllocatedColumn) the space is slightly larger than 8 Mb. Now flip the image and observe that the value is larger. Because there are only 13 images in the application, the memory leakage is limited. This is the worst way to leak memory, because there will never beOutOfMemoryErrorInstruct us about memory leakage.

Create a heap

Let's use heap to track problems. ClickDump hprof FileClick, select the Save path, and then executehprof-convCommand. In this example, the independent version of MAT (version 1.0.1) is used for heap analysis.
Download the mat download site.

If you have run ADT (the plugin version of ddms) and mat has been installed in eclipseDump hprof FileThe conversion is automatically completed (using hprof-Conv), and the converted hprof file is opened in eclipse (using mat ).

Use mat to analyze heap

Start mat and load the converted hprof file. MAT is a powerful tool, but its features are beyond the scope of this article, so here only shows a way to detect memory leakage: histogram. The histogram displays the class list, which are sorted by the number of instances.Shallow heap(Total heap size used by all instances ),Retained heap(The total size of the heap in the active State used by all instances, including the referenced other objects)

If we sort the shallow heap, we can see that:byte[]The instance is the highest. Because in Android 3.0 (honeycomb), the pixel data of bitmap is stored in the byte array (which was not put into the Dalvik heap in earlier versions), based on the size of these objects, A security bet is made. For the leaked bitmap, the byte array is considered as the backup memory.

Right-click byte [] class and selectList objects> with incoming referencesTo generate a list Of all byte arrays in the heap. We can sort the list based on the usage of shallow heap.

Select one of the large objects in byte [] and trace them all the way. Then, you will see the entire path from the root to the object-a reference chain for storing the active object. Here is our bitmap cache:

Mat cannot tell us exactly that this is a leak because it does not know whether these objects need to be done by programmers. In this case, the cache of other applications uses a large number of heaps. Therefore, we may consider limiting the cache size.

Use mat for heap to compare

When debugging memory leaks, it is sometimes useful to compare the heap status at two different time points. To do this, create two independent hprof files (do not forget to use hprof-Conv to convert them ).

Here is how to use mat to compare two heap transformations (a bit complicated ):

1) open the first hprof file (UseFile> open heap dump)

2) Open the Histogram

3) in the navigation history window (if not visible, useWindow> navigation historyOpen), right-clickHistogramAnd selectAdd to compare basket

4) open the second hprof file and repeat steps 2) and 3 ).

5) switch to the Compare basket window, and clickCompare the results(In the upper-right corner of the window, the red "!" Icon)

Summary

In this article, we show you how allocation tracker and heap transform bring you a better feeling when analyzing application memory leaks. It also shows how to use the eclipse mat tool to track memory leaks in applications. MAT is a powerful tool. Here we just introduce some of its features. If you want to learn more, read the following articles:

1) memory analyzer news: Official eclipse mat project blog

2) Markus Kohler's Java performance research blog: There are many useful articles, including: Analysing the memory usage of Android applications with the eclipse memory analyzer and 10
Useful tips for the eclipse memory analyzer.

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.