首先先看下TypedArray实例化源码:
static TypedArray obtain(Resources res, int len) { TypedArray attrs = res.mTypedArrayPool.acquire(); if (attrs == null) { attrs = new TypedArray(res); } attrs.mRecycled = false; // Reset the assets, which may have changed due to configuration changes // or further resource loading. attrs.mAssets = res.getAssets(); attrs.mMetrics = res.getDisplayMetrics(); attrs.resize(len); return attrs; }
可以看出,TypedArray的实例是从一个Array Pool中 获取的,池的描述如下:
// Pool of TypedArrays targeted to this Resources object. final SynchronizedPool<TypedArray> mTypedArrayPool = new SynchronizedPool<>(5);池中默认大小为5。 程序在运行时维护了一个 TypedArray的池,程序调用时,会向该池中请求一个实例,用完之后,调用 recycle() 方法来释放该实例,从而使其可被其他模块复用。
那为什么要使用这种模式呢?答案也很简单,TypedArray的使用场景之一,就是上述的自定义View,会随着 Activity的每一次Create而Create,因此,需要系统频繁的创建array,对内存和性能是一个不小的开销,如果不使用池模式,每次都让GC来回收,很可能就会造成OutOfMemory。