Android LruCache cache size parameter
Asked Answered
E

2

6

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

Easygoing answered 3/8, 2016 at 14:58 Comment(0)
S
6

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.

Selenium answered 3/8, 2016 at 15:13 Comment(1)
Got it! Thank you! Then that means I'd have to override sizeOf method instead. There was no mentioning of this with the tutorial I'm following probably it is already an older method.Easygoing
H
1

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.

Hildick answered 3/8, 2016 at 18:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.