androidgarbage-collectiontypedarray

Why should a TypedArray be recycled?


This answer tells me that calling the recycle() method of a TypedArray allows for it to be garbage collected. My question is why TypedArray specifically needs a method for it to be garbage collected? Why can't it just wait to be garbage collected like a regular object?


Solution

  • 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.