Reputation: 531
Does Android have a Garbage Collection
? Is it efficient or should you set objects to null
when not needed?
For example, I have an ImageView
iv
. I set an image bitmap with
iv.setImageBitmap(some_function_that_returns_a_bitmap_that_is_newly_created())
and after some time I run the same function
iv.setImageBitmap(some_function_that_returns_a_bitmap_that_is_newly_created())
What happens to the Bitmap that was created by the first function some_function_that_returns_a_bitmap_that_is_newly_created()
? Does the garbage collection remove it? Does it make a difference, to do this
Bitmap temp =some_function_that_returns_a_bitmap_that_is_newly_created();
iv.setImageBitmap(temp);
temp = null;
...
temp =some_function_that_returns_a_bitmap_that_is_newly_created();
instead?
Does it make a difference, to do this
Bitmap temp =some_function_that_returns_a_bitmap_that_is_newly_created();
...
temp = null;
...
temp =some_function_that_returns_a_bitmap_that_is_newly_created();
instead of this
Bitmap temp = some_function_that_returns_a_bitmap_that_is_newly_created();
...
temp = some_function_that_returns_a_bitmap_that_is_newly_created();
?
Upvotes: 1
Views: 420
Reputation: 6715
Yes, Android's VM does garbage collection. There are very, very few places where nulling the reference to an object is an effective way to save space... but you've hit one of them.
Bitmaps are large and it, very definitely, can be helpful to null a reference to one that you no longer need.
In the code that you show in the second example, your intuition is correct, the reference to the old bitmap will keep it from being recycled until the reference to the new bitmap is assigned to temp
. That means that at some point, both are in memory.
The first version of your code does not have that problem.
Edited to add: btw, standard practice in Java is camelCasing, not under_scoring ;-P
Upvotes: 1