性能提高:(二)资源来自本地

本文探讨了在本地获取资源与从服务器端获取资源在性能上的区别,指出服务器资源获取需额外的openConnection操作,导致较长时间的延迟。通过使用线程安全的Map容器,本地资源获取变得高效便捷。

资源来自本地的时候,那么和前面一篇所讲的,在性能上有什么不同呢。

其实也有那么一小点不同,即:从服务器端获取的资源要建立一个openConnection,然后分析数据,将图片等资源下载下来,这显然很耗时。等图片这些资源下载完后,接下来的操作和性能问题就和本地资源获取一样了。(大侠们,说得不对请给与批评)

所以在本地获取如assets里的资源的时候,只需要一个线程安全的Map即可。

下面给出代码:

public class TestResourceUtils {

	// 线程安全的map容器
	private static Map<Class<?>, Map<String, Integer>> mResourceCache = null;
	
	// type 可以是R.drwable R.Layot ect..
	public static int getIdentifier(Class<?> type, String name) {
		// 初始化
		if(mResourceCache == null){
			synchronized (TestResourceUtils.class){
				if(mResourceCache == null){
					mResourceCache = new ConcurrentHashMap<Class<?>, Map<String, Integer>>();
				}
			}
		}
		// 查找某一类型的资源
		Map<String, Integer> typeCache;
		if (!mResourceCache.containsKey(type)) {
			typeCache = new ConcurrentHashMap<String, Integer>();
			mResourceCache.put(type, typeCache);
		}
		else {
			typeCache = mResourceCache.get(type);
		}

		if (typeCache.containsKey(name)) {
			return typeCache.get(name);
		}
		
		// 从R文件中读出
		try {
			Field field = type.getField(name);
			int resId = field.getInt(null);

			if (resId != -1) {
				typeCache.put(name, resId);
			}

			return resId;
		}
		catch (Exception e) {
			Log.e("MovieDemo", "Failed to retrieve identifier: type=" + type + " name=" + name, e);
			return -1;
		}
	}
}

使用例子:

ImageView image=(ImageView)vi.findViewById(R.id.image);
image.setImageResource(ResourceUtils.getIdentifier(R.drawable.class, "icon"));


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值