Use of setImageBitmap in ImageView

Sriram Ramasubramanian sramasubramanian at mozilla.com
Mon Nov 4 11:25:56 PST 2013


Hello Fennec-devs,

While monitoring some memory issues last week, I ran into this. We had a piece of code for resetting the image in an ImageView:

imageView.setImageBitmap(null);

This did the intended thing. The image was cleared, and the UI showed no problems.

But under the hood, Android does:

    @android.view.RemotableViewMethod
    public void setImageBitmap(Bitmap bm) {
        // if this is used frequently, may handle bitmaps explicitly
        // to reduce the intermediate drawable object
        setImageDrawable(new BitmapDrawable(mContext.getResources(), bm));
    }
As you can see, there is no check on whether “bm” is null or not. This creates a “BitmapDrawable” object. The BitmapDrawable internally creates “State” objects and “Paint” objects. All of these aren’t even going to be used, as we are just clearing up the image in the view. Now think of resetting the ImageView (like favicon), whenever the row goes out of visible area inside a list (recycling). With a small scroll, we would be creating endless objects while recycling. (HORRORRR!!!) So, instead of using setImageBitmap(), please use setImageDrawable()  in such cases.

Note: setImageResource(android.R.color.transparent) is also valid. But, Android decodes the resource in the UI thread, and might not be good for performance purposes.

Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=934001

Thanks,
Sriram.


More information about the mobile-firefox-dev mailing list