Showing posts with label garbage collector. Show all posts
Showing posts with label garbage collector. Show all posts

Wednesday, September 8, 2010

Using arraylists properly with android


Late post so ill keep it short.

Android development hinges on being efficent with memory. Declaring objects in a loop is not efficient. If you use a foreach loop with an arraylist, you are creating an iterator each time you run through the loop. Instead, loop through your arraylist using a for loop like this:

for(I =0; I<mylist.size();I++){

       Myobject=mylist.get(I);

...

)

That will prevent memory leaks and keep your game or app running smoothley since the garbage collector will be swift.  See my other post for how to track all memory leaks while developing with android.

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