Search code examples
androidandroid-lru-cache

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..


Solution

  • 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.