我正试图在android上学习一个2年前的关于LruCache使用的教程,到目前为止我在谷歌上搜索过的一些示例有相同的方法,即传递一个转换为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();
}
}
我想知道哪一个是正确的计量单位。如有任何答案,我们将不胜感激。。
sizeOf
来确定缓存的当前大小,以及缓存是否已满。(即,对高速缓存中的每个项目调用sizeOf
,并将其相加以确定总大小)。因此,构造函数的正确值取决于sizeOf
的实现。
默认情况下,sizeOf
总是返回1,这意味着在构造函数中指定的int maxSize
只是缓存可以容纳的项目数。
在本例中,sizeOf
已被覆盖以返回每个位图中的字节数。因此,构造函数中的int maxSize
是缓存应保持的最大字节数。
以下内容来自https://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
正如你所看到的,原理是LruCache
需要一个int。因为内存可能太大,无法用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。