Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android LruCache cache size parameter

I am trying to follow a 2 year old tutorial on android regarding the usage of LruCache and some samples I have googled so far have the same method which is to pass an value(int) that is converted to KiB.

final int maxMemory = (int)(Runtime.getRuntime().maxMemory() / 1024); 
final int cacheSize = maxMemory / 8; //use 1/8th of what is available
imageCache = new LruCache<>(cacheSize);

However as taken from Google's documentation, the passed int value seems to be converted to bytes (from MiB): https://developer.android.com/reference/android/util/LruCache.html

int cacheSize = 4 * 1024 * 1024; // 4MiB
LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(cacheSize) {
   protected int sizeOf(String key, Bitmap value) {
       return value.getByteCount();
   }
}

I would like to know which one is the correct unit of measurement. Any answers would be greatly appreciated..

like image 272
Rei Avatar asked Aug 03 '16 14:08

Rei


2 Answers

An LruCache uses the method sizeOf to determine the current size of the cache, and whether or not the cache is full. (i.e., sizeOfis called on each item in the cache and added up to determine the total size). Thus, the correct value for the constructor depends on the implementation of sizeOf.

By default, sizeOf always returns 1, meaning that the int maxSize specified in the constructor is simply the number of items the cache can hold.

In the example, sizeOf has been overridden to return the number of bytes in each bitmap. Thus, the int maxSize in the constructor is the maximum number of bytes the cache should hold.

like image 88
chessdork Avatar answered Oct 15 '22 09:10

chessdork


What you are following comes from https://developer.android.com/training/displaying-bitmaps/cache-bitmap.html

As you can see, the rationale is that LruCache needs an int. Because memory can be to big to address bytes with ints, it considers kilo bytes instead. So:

final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;

But also, in the same training,

protected int sizeOf(String key, Bitmap bitmap) {
    // The cache size will be measured in kilobytes rather than
    // number of items.
    return bitmap.getByteCount() / 1024;
}

The size of the bitmap is also expressed in kilo bytes.

In the class documentation, the author uses bytes because 4.2^20 fits in an int.

like image 22
njzk2 Avatar answered Oct 15 '22 09:10

njzk2