Android memory analysis tool

Source: Internet
Author: User

The Dalvik Virtual Machine supports garbage collection, but this does not mean you don't have to worry about memory management. Pay special attention to the memory usage of mobile devices. The memory space of mobile phones and tablets is limited.

In this article, let's take a look at how some of the memory profiling tools in the android SDK help us trim the memory usage of the application.

I. Memory leakage

Some memory usage problems are obvious. For example, if the app has a memory leak every time the user touches the screen, the outofmemoryerror may be triggered and the program crashes.

The other issues are subtle, but they may only reduce the performance of the application and the entire system (when the Garbage Collector runs at a high frequency and for a long time ).



Ii. Memory tools

The android SDK provides two main tools for analyzing application memory usage: Allocation tracker and heap dumps.

1) allocation tracker is very useful, especially when you want to get a perceptual knowledge of the memory allocation of the program within a certain period of time. However, it cannot give you any information about the overall situation of the program heap. For more information about allocation tracker, see tracking memory allocations.


2) Heap dumps: it is a more powerful memory analysis tool. A heap dump is a snapshot of the program heap, Which is saved as a binary format called hprof. Dalvik uses a similar format, but not exactly the same. Here is the Java hprof tool. There are many ways to generate a heap dump for the runtime application, one of which is to use the dump hprof file button in ddms. If you want to generate more precise dump data, android. OS. debug. dumphprofdata () method.

To analyze heap dump, you can use some standard tools such as jhat or eclipse MAT (memory analyzer tool ). However, you must first convert the. hprof file from the Dalvik format to the j2se hprof format. You can use the hprof-Conv tool provided by the android SDK. For example:

Hprof-Conv dump. hprof converted-dump.hprof



Iii. Memory debugging

When Dalvik is running, programmers cannot explicitly allocate and release memory, so the memory leakage here is different from that in C and C ++. In your code, memory leakage means that you retain a reference to a class object that is no longer needed. Sometimes, a single reference will impede GC from reclaiming a large number of objects.

Let's take a practical example. The example app honeycomb gallery sample app provided in the android SDK. It is a Photo Gallery program used to demonstrate the use of some new honeycomb APIs. (To download and compile the code, please refer to these commands) We will intentionally Add a memory leak in the program and then demonstrate how to debug it.

Imagine that we want to modify the program so that it can download images from the network. To make it more flexible, we can consider implementing a cache to save recently viewed images. java makes some small modifications to achieve this goal. At the top of the class, we add a new static variable:

Private Static hashmap <string, bitmap> sbitmapcache = new hashmap <string, bitmap> ();

Here is where we save the cache. Now we can modify the updatecontentandrecyclebitmap () method so that it can check whether the data already exists before downloading it. If it does not exist, download it and add the data to the cache.

Void updatecontentandrecyclebitmap (INT category, int position) {<br/> If (mcurrentactionmode! = NULL) {<br/> mcurrentactionmode. finish (); <br/>}</P> <p> // get the bitmap that needs to be drawn and update the imageview. </P> <p> // check if the bitmap is already in the cache <br/> string bitmapid = "" + category + ". "+ position; <br/> mbitmap = sbitmapcache. get (bitmapid); </P> <p> If (mbitmap = NULL) {<br/> // It's not in the cache, so load the bitmap and add it to the cache. <br/> // danger! We add items to this cache without ever removing any. <br/> mbitmap = directory. getcategory (category ). getentry (position ). getbitmap (getresources (); <br/> sbitmapcache. put (bitmapid, mbitmap); <br/>}</P> <p> (imageview) getview (). findviewbyid (R. id. image )). setimagebitmap (mbitmap); <br/>}

Here we intentionally introduced a memory leakage problem: we added images to the cache but never removed them. In real applications, we can use some method to limit the cache size.

 

Iv. Check heap for ddms

Dalvik debug monitor server (ddms) is one of the main Android debugging tools and is part of ADT plugin for eclipse, the independent program version can also be found under tools/in the root directory of the android SDK. For more information about ddms, see use ddms.

We will use ddms to check the heap usage of this application. You can use the following two methods to start ddms:

  • From Eclipse: Click window-> open perspective-> other...-> ddms
  • From the command line: Runddms(Or./ddmsOn MAC/Linux) intools/Directory

On the left-side pane, select com. example. Android. hcgallery, and click show heap updates in the toolbar. In this case, switch to the VM heap page of ddms, which will display some basic data of heap memory after each GC.

To view the data after the first GC, click the cause GC button:

We can see that the current value (allocated column) is more than 8 Mb. Moving the photo now, we can see that the data is increasing, because only 13 photos are in the program, so the leaked memory is only so large. To some extent, this is the worst kind of memory leakage, because we cannot get outofmemoryerror to remind us that memory overflow is happening now.



5. Generate heap dump

To use heap dump to track this issue, you must first save the hprof file:

Click the dump hprof file button on the ddms toolbar, select the file storage location, and then run hprof-Conv. In this example, we use an independent mat version (version 1.0.1) and mat for download.

If you use ADT (which includes the ddms plug-in) and install mat in eclipse, click "Dump hprof" to automatically perform the conversion (using hprof-Conv ), at the same time, the converted hprof file will be opened in eclipse (it is actually opened with Mat ).

 

6. Mat analysis heap dumps

Start mat and load the hprof file we just generated.

MAT is a powerful tool that describes all its features beyond the scope of this article, so I just want to demonstrate a method you can use to detect leaks: histogram view. It displays a list of sortable class instances, including: shallow heap (total memory usage of all instances) or retained heap (total memory allocated to all class instances, including all the referenced objects ).

If we sort by shallow heap, we can see that the byte [] instance is at the top. Since Android 3.0 (honeycomb), the pixel data of bitmap is stored in the byte array (previously stored in the heap of Dalvik). Therefore, it is determined based on the size of this object, needless to say, it must be our leaked bitmap.

Right-click the byte [] class and select list objects-> with incoming references. It will generate a list of all the byte arrays on the heap, in the list, we can sort by shallow heap usage.

Select and expand a large object, which will display the path from the root to this object-is a chain that ensures the object is valid. Note that this is our bitmap cache!

Mat won't tell us clearly that this is a leak because it doesn't know whether the program needs this thing or not. Only the programmer knows it.

In this case, the large amount of memory used by the cache will affect the subsequent applications, so we can consider limiting the cache size.

 

7. Mat compares two heap dumps

When debugging memory leaks, it is sometimes useful to compare the heap status in two places in a timely manner. In this case, you need to generate two separate hprof files (do not forget the conversion format). The following describes how to compare the content of two heap dumps in mat (a little complicated ):

  1. First hprof file (using file-> open heap dump)
  2. Open histogram View
  3. In the navigation history view (from WINDOW> navigation history if not visible), right-click histogram and select Add to compare basket.
  4. Open the second hprof file and redo steps 2 and 3
  5. Switch to the Compare basket view and click Compare the results (red in the upper right corner of the View "! "Icon ).



VIII. Summary

This article shows how allocation tracker and heap dumps give you a perceptual knowledge of program memory usage. I also showed that mat can help chase memory leaks in our program.

MAT is a powerful tool, and I just touched some skins. If you want to learn more, I suggest reading the following articles:

  • Official eclipse mat project blog: Memory analyzer blog or blog.sixxs.org
  • Markus Kohler's blog on Java performance: Java performance blog or blog.sixxs.org
Note: The above two blog websites may be "walled" and need to be accessed through VPN or IPv6 + sixxs.org proxy
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.