Tuesday, September 7, 2010

How to Find Memory Leaks in Android Applications

While working on a game, I noticed the Garbage Collector was causing significant delays while cleaning up memory. The GC is used by Java to free up memory that has been taken by objects that your program can no longer access. Since a game is inherently developed in a loop, it is very easy to create unnecessary objects over and over. Once these take up too much memory, the GC must run to free up more memory for the App. Unfortunately this can cause a pause in your game, or even a simple app.

The android SDK comes with a great tool to find these memory leaks.

-Just go to your tools directory under your SDK folder, and open the ddms. Make sure you don't already have eclipse running, as only one debugger can attach at a time.

-Run your application on your attached device (your phone)

-Select your application in the application list on the left side of the ddms

-Select the "allocation tracker" tab in the ddms

-click "Start Tracking" in the allocation tracker tab

-Interact with your application on your device for a while

-click "Get Allocations" in the ddms

This will list the memory allications, in descending size. You can click on each allocation and the full stack trace is given, which allows you to determine what line of what class the allocation was made. Very easy! Now go to that line and smack yourself in the forehead for that worthless declaration, and become a greener programmer!

This will make your game/app run much smoother. However, remember that the garbage collector normally runs, so you can never get rid of all GC collections.

original post: Tracking Memory Leaks

No comments:

Post a Comment