Reputation: 13
In my Android app I have a function to get a bitmap from an ImageView and TextView, then save it to the SDCard. At the end of the function I am currently calling recycle() on the bitmap objects and destroyDrawingCache() on the ImageView, as follows:
b1.recycle();
bitmap.recycle();
imgView.destroyDrawingCache();
b1 and bitmap are Bitmap objects, and they are local variables. imgView is an ImageView object, and it is a field. imgView gets recreated often as the application runs. Is it a good idea, performance and memory-wise, to include these three lines of code? Or will the garbage collector do the work automatically so that including them will just slow the application down as it has to make three method calls?
Upvotes: 1
Views: 2529
Reputation: 133580
Quoting from the docs
http://developer.android.com/training/displaying-bitmaps/manage-memory.html
On Android 2.3.3 (API level 10) and lower, using recycle() is recommended. If you're displaying large amounts of bitmap data in your app, you're likely to run into OutOfMemoryError errors. The recycle() method allows an app to reclaim memory as soon as possible.
Android 3.0 (API Level 11) introduces the BitmapFactory.Options.inBitmap field. If this option is set, decode methods that take the Options object will attempt to reuse an existing bitmap when loading content. This means that the bitmap's memory is reused, resulting in improved performance, and removing both memory allocation and de-allocation. In honeycomb and later versions bitmap pixel data is allocated on the heap. So you don't need to call recycle in this case. When gc kicks in it will free the memory allocated for bitmaps.
Its the job of the garbage collector to free memory. When it needs to reclaim memory garbage collector kicks in. GC deos mark and sweep. You can check the logcat.
You can see the pause times. Large the heap more frequently gc kicks in and more frequent pause times.
GC_CONCURRENT freed <1K, 14% free 21220K/24455K, paused 6ms+26ms
GC_CONCURRENT : Jumps in because Heap is full
14% free 21220K/24455K After this collection 14% of memory is free. Check the heap usage.
paused 6ms+26ms Time taken to collect garbage.
There is a talk on this topic @ https://www.youtube.com/watch?v=_CruQY55HOk
Upvotes: 2