Why should a TypedArray be recycled?

五迷三道 提交于 2019-11-30 13:05:12

This is required for caching purporse. When you call recycle it means that this object can be reused from this point. Internally TypedArray contains few arrays so in order not to allocate memory each time when TypedArray is used it is cached in Resources class as static field. You can look at TypedArray.recycle() method code:

/**
 * 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;
        }
    }
}

So when you call recycle your TypedArray object is just returned back to cache.

@Andrei Mankevich I just check the newest version of Android SDK, and it seems there are some changes make to recycle(). Please check the below codes:

/**
 * 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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!