为什么TypedArray应该被回收?

时间:2012-12-10 16:56:09

标签: android garbage-collection typedarray

This answer告诉我,调用TypedArray的recycle()方法允许对其进行垃圾回收。我的问题是为什么TypedArray特别需要一个方法来进行垃圾回收?为什么它不能等待像常规对象一样被垃圾收集?

2 个答案:

答案 0 :(得分:6)

这是缓存purporse所必需的。当您调用recycle时,意味着可以从这一点重用此对象。内部TypedArray包含少量数组,因此为了在每次使用TypedArray时不分配内存,它将作为静态字段缓存在Resources类中。您可以查看TypedArray.recycle()方法代码:

/**
 * Give back a previously retrieved StyledAttributes, for later re-use.
 */
public void recycle() {
    synchronized (mResources.mTmpValue) {
        TypedArray cached = mResources.mCachedStyledAttributes;
        if (cached == null || cached.mData.length < mData.length) {
            mXml = null;
            mResources.mCachedStyledAttributes = this;
        }
    }
}

因此,当您致电recycle时,您的TypedArray对象才会返回缓存。

答案 1 :(得分:2)

@Andrei Mankevich 我只是检查最新版本的Android SDK,似乎对recycle()做了一些更改。请检查以下代码:

/**
 * Recycle the TypedArray, to be re-used by a later caller. After calling
 * this function you must not ever touch the typed array again.
 */
public void recycle() {
    if (mRecycled) {
        throw new RuntimeException(toString() + " recycled twice!");
    }

    mRecycled = true;

    // These may have been set by the client.
    mXml = null;
    mTheme = null;

    mResources.mTypedArrayPool.release(this);
}