为什么应该回收TypedArray?

11

这个答案告诉我,调用TypedArray的recycle()方法可以让它被垃圾回收。我的问题是为什么TypedArray需要特定的方法才能进行垃圾回收?为什么不能像普通对象一样等待被垃圾回收?

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对象只是返回到缓存中。


1
/**
  • 回收TypedArray,以便稍后的调用者重复使用。调用此函数后,您绝不能再次触摸类型数组。 */ public void recycle() { if (mRecycled) { throw new RuntimeException(toString() + " 重复回收!"); } mRecycled = true; // 这些可能已由客户端设置。 mXml = null; mTheme = null; mResources.mTypedArrayPool.release(this);
}
- Sam003

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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接