Saturday, March 9, 2013

BitmapFactory.decodeResource performance

While checking the performance of my app I've noticed BitmapFactory.decodeResource is relatively slow. So I've checked the alernative, instead of loading my PNG files as resources, putting them in /assets/ folder and loading using BitmapFactory.decodeStream.

Here are the test functions:

void decodeResource() {
 Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.tile, null);
 originalBitmap.recycle();
}
void decodeStream() {
 InputStream ins = null;
 try {
  ins = getAssets().open("tile.png");

  Bitmap originalBitmap = BitmapFactory.decodeStream(ins);
  originalBitmap.recycle();
 } catch (final IOException e) {
  e.printStackTrace();
 } finally {
  if (ins != null)
   try {
    ins.close();
   } catch (IOException e) { }
 }     
}

Running both functions 50 times to load a small PNG file (230*230) on Nexus Galaxy running Android 4.2.2:
  • decodeResource: 1793ms 
  • decodeStream: 188ms 
Conclusion: decodeStream is almost x10 faster than decodeResource.

2 comments:

daybreak1030 said...

Hi I am a beginner in Android.How could I run a single method 50 methods? And if what you said is a real problem,why decodeResource is so popular? Thx:D

Sagi said...

@王晓方 -
(1) I ran it in a loop 50 times.
(2) I didn't say decodeResource doesn't work, only that there's a faster way to do the same job (at least for Android 4.3 and older).