11

这个答案告诉我调用recycle()TypedArray 的方法可以对其进行垃圾收集。我的问题是为什么 TypedArray 特别需要一种方法来对其进行垃圾收集?为什么不能像普通对象一样等待垃圾收集?

4

2 回答 2

9

这是缓存目的所必需的。当你调用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对象只是返回到缓存中。

于 2012-12-10T17:06:34.593 回答
4

@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);
}
于 2015-07-14T19:32:03.567 回答