为什么Android使用Ints而不是Enums所以原因有两个(至少):

2022-09-04 03:11:23

阅读有关Android的信息,我可以看到框架的许多部分使用常量作为返回值或配置值(如这里),而不是,据我所知,这是一个更好的选择,原因有很多,可以在网络上找到,就像这样intSTART_REDELIVER_INTENTenum

所以这让我想知道...为什么谷歌决定使用这么多而不是?int'senum's


答案 1

直接从文档中提取

Enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.

http://developer.android.com/training/articles/memory.html#Overhead

编辑:

也是罗曼·盖伊(Roman Guy)的一次演讲中的幻灯片

https://speakerdeck.com/romainguy/android-memories?slide=67


答案 2

int 上的操作比枚举上的操作快很多倍。

自己判断。每次创建枚举时,您至少要创建:

1) Class-loader for it. 
2) You keep this object in memory. 
3) Since enum is static anonymous class - it will always hang in your memory (sometimes even after you close the application.) 

关于 .在此类中,标志主要用于比较,并将结果返回到上面的类 ()。但基本上,如果你深入研究Android SDK的肠道,你会发现几乎所有这些标志都被用来进行旁班操作ServiceContextWrapper

即使在Java中,在JDK中使用二进制移位操作:

/**
 * Max capacity for a HashMap. Must be a power of two >= MINIMUM_CAPACITY.
 */
private static final int MAXIMUM_CAPACITY = 1 << 30;

你也可以在Android SDK中查看Window类

/**
 * Set the container for this window.  If not set, the DecorWindow
 * operates as a top-level window; otherwise, it negotiates with the
 * container to display itself appropriately.
 *
 * @param container The desired containing Window.
 */
public void setContainer(Window container) {
    mContainer = container;
    if (container != null) {
        // Embedded screens never have a title.
        mFeatures |= 1<<FEATURE_NO_TITLE;
        mLocalFeatures |= 1<<FEATURE_NO_TITLE;
        container.mHasChildren = true;
    }
}

/** The default features enabled */
@SuppressWarnings({"PointlessBitwiseExpression"})
protected static final int DEFAULT_FEATURES = (1 << FEATURE_OPTIONS_PANEL) |
        (1 << FEATURE_CONTEXT_MENU);

所以原因有两个(至少):

  • 更少的内存消耗。

  • 由于按位操作,工作速度更快。