首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么要回收TypedArray?

为什么要回收TypedArray?
EN

Stack Overflow用户
提问于 2012-12-11 00:56:09
回答 2查看 7.8K关注 0票数 10

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-11 01:06:35

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

代码语言:javascript
复制
/**
 * 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对象只是返回到缓存。

票数 7
EN

Stack Overflow用户

发布于 2015-07-15 03:32:04

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

代码语言:javascript
复制
/**
 * 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);
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13805502

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档