Android LruCache缓存大小参数

6

我正在尝试遵循一个关于安卓应用程序使用LruCache的2年前的教程,一些我搜索到的示例都有相同的方法,即传递被转换为KiB的值(int类型)。

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

然而从谷歌文档中得知,传递的int值似乎被转换为字节(从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();
   }
}

我想知道哪一个是正确的计量单位。非常感谢提供任何答案。
2个回答

6
一个 LruCache 使用方法 sizeOf 来确定缓存的当前大小以及缓存是否已满。(即在缓存中对每个项目调用sizeOf并将其加起来以确定总大小。)因此,构造函数的正确值取决于sizeOf 的实现。
默认情况下,sizeOf 始终返回1,这意味着在构造函数中指定的int maxSize 只是缓存可以容纳的项目数。
在此示例中,sizeOf 已被重写为返回每个位图中的字节数。因此,在构造函数中的int maxSize 是缓存应该保留的最大字节数。

明白了!谢谢!那就意味着我需要覆盖sizeOf方法。在我正在跟随的教程中没有提到这一点,可能是因为它已经是一个旧方法了。 - Rei

1
你正在关注的内容来自https://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
正如您所看到的,其基本原理是LruCache需要一个整数。由于内存可能太大而无法使用整数寻址字节,因此它考虑使用千字节。因此:
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;

但是,在同一次培训中,

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

位图的大小也以千字节表示。
在类文档中,作者使用字节,因为4.2 ^ 20适合一个int。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接