6

我正在尝试遵循有关 LruCache 使用的 2 年历史的 android 教程,到目前为止我在 Google 上搜索过的一些示例具有相同的方法,即传递一个转换为 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();
   }
}

我想知道哪个是正确的计量单位。任何答案将不胜感激..

4

2 回答 2

6

LruCache 使用该方法sizeOf来确定缓存的当前大小,以及缓存是否已满。(即,sizeOf在缓存中的每个项目上调用并相加以确定总大小)。因此,构造函数的正确值取决于sizeOf.

默认情况下,sizeOf总是返回 1,这意味着int maxSize在构造函数中指定的只是缓存可以容纳的项目数。

在示例中,sizeOf已被覆盖以返回每个位图中的字节数。因此,int maxSize构造函数中的 是缓存应保存的最大字节数。

于 2016-08-03T15:13:52.977 回答
1

您关注的内容来自https://developer.android.com/training/displaying-bitmaps/cache-bitmap.html

如您所见,基本原理是LruCache需要一个 int。因为内存可能很大,无法用整数寻址字节,所以它会考虑千字节。所以:

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。

于 2016-08-03T18:58:33.673 回答