For large objects, should I use WeakReferences or dispose until I’m done?

Hey everyone,

Short post today. I’m just giving some food for thought.

This post has come up since I’ve just done something that might be interesting for those of you. Especially, those of us who are dealing with high resolution images.

So, I’ve come across a very similar problem today along with what I’ve done before. Except before, I was always recycling and/or disposing my images. Now with what I had done before, these have worked quite well for me, though sometimes I can get unpredictable results like app crashes.

Even in RecyclerView, depending on the image being loaded, you can end up with a race condition. Hey guys, I get it; your image loaded is different than what you chose, so in this case I’d record the position under OnViewAttachedToWindow.

Now for the big question! Dispose my image, or use a WeakReference? The answer I’ll give you is, it really depends on your situation.

Let’s say I have a ViewHolder that also includes a bitmap that my ImageView will reference. In this case, I must keep track of the bitmap mainly in OnBindViewHolder and OnViewRecycled. Sure, this is more maintenance, but it helps me learn the inner workings of how a RecyclerView and its adapter works. Granted, this solution is good if you’re loading multiple images in your RecyclerView.

Now then, let’s revisit our RecyclerView that has a SnapHelper that loads one image (so like a full-page screen) per swipe. In this case, I am able to make a static bitmap which is under a WeakReference, and then therefore it’ll just load when I need it, or throw the bitmap away some time later when the system knows I’m really done with it. I played with this, and the Android Profiler provided good results with ram, along with my emulator that had a RAM threshold of 256MB! If the image nulled out for some odd reason, hey, I didn’t do it. Now having one image per page, one bitmap makes sense. If there were multiple images, I’d already be able to tell that this wouldn’t work so well.

So there you have it! Take your pick, and make it efficient 🙂

Until next time!

Brian.