0

Android 上用于缓存图像的最佳 BitmapLRU图像缓存大小是多少?我的目标是 sdk 2.3.5+ 基本上 10+ 设备。目前我正在采取这两个计算中的较大数量,如下所示。1/8 是避免内存不足错误的安全百分比吗?

这是我现在的计算方式:

private static int calculateImageCacheSize(Context ctx)
{
    // Gets the dimensions of the device's screen
    DisplayMetrics dm = ctx.getResources().getDisplayMetrics();
    int screenWidth = dm.widthPixels;
    int screenHeight = dm.heightPixels;

    // Assuming an ARGB_8888 pixel format, 4 bytes per pixel
    int size = screenWidth * screenHeight * 4;

    // 3 bitmaps to store therefore multiply bitmap size by 3
    int cacheSize = size * 3;

    int cachePercentOfMemory = getPercentageOfTotalMemory(8);
    int retCacheSize = cacheSize;
    if (retCacheSize < cachePercentOfMemory)
        retCacheSize = cachePercentOfMemory;
    return retCacheSize;
}

public static int getPercentageOfTotalMemory(int divider)
{
     final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
     final int cacheSize = maxMemory / divider;
     return cacheSize;
}
4

1 回答 1

0

没有一个“正确”的答案,实际上取决于您的应用程序在做什么。如果它有很多网络连接,有复杂的数据结构,解码很多位图......等等,那么代码本身会消耗相当多的内存,将图像缓存大小设置为 1/8 应该是合理的。但是,如果您的应用程序非常简单,您可能会增加为缓存分配的内存量。

因此,如果您真的担心它,唯一知道的方法是让测试测试您的应用程序,看看哪种配置最适合这个特定的应用程序。

于 2013-08-03T02:10:34.820 回答