Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickly unload bitmaps from memory

I am creating this Android game in Java. I have quite a lot of images but don't need to use them all at once so I have created a Resource Manger class which takes care of the Bitmaps that are in use. However, I have found it quite slow to clear the Bitmap out of the memory. I am currently doing something like this:

bitmap.recycle()
bitmap = null

System.gc (also tried Runtime.getRuntime().gc())

Firstly, is there any way to quicker unload the bitmaps from the memory or is it possible to somehow check if they actually ARE cleared so I can make the loading screen depend on that as well?

like image 270
Rasmus Avatar asked Dec 19 '12 23:12

Rasmus


1 Answers

There is no guarantee that the garbage collector will actually be run when we attempt for System.gc() as gc() expects certain preconditions like resource hunger. So it is quite obvious that calling gc() is just wasting critical CPU Cycles. As a developer we can make unnecessary objects for gc collectable by nullifying the references.

There are couple of optimization techniques that can be helpful while creating a gaming system(game).

  1. Use Texture. Here is an example.

  2. Use Sprite and SpriteSheets( It gives less overhead to the system than loading individual bitmaps). many open source game engines are there who uses this.If you don't want to use them get an idea how to create from scratch from these sources.

  3. Use these standard android doc for how to Loading Large Bitmaps Efficiently and Caching Bitmaps for better usage of bitmap. The idea is when users device is not efficient enough to handle the amount of processing and/or the memory is less for your game you can always scale down the bitmap(compromise with quality for better response).

  4. Always test your app against memory leak problems. Here is a nice post that will help.

  5. Keep InMemory(don't release once used) items that are used several times inside the game in the same scene. The reason is it takes lot of time to load images into the memory.

Hope this will help you.

like image 107
Ajay Kumar Meher Avatar answered Oct 07 '22 07:10

Ajay Kumar Meher