为什么Android使用Ints而不是Enums

阅读关于Android我可以看到框架的许多部分使用int常量作为返回值或configuration值( 就像在这里 START_REDELIVER_INTENT ),而不是一个enum ,据我所知,是一个更好的select,原因很多可以在networking上find, 就像这样 。

所以这让我怀疑…为什么谷歌决定使用这么多int's而不是enum's呢?

直接从文档中拉出来

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

编辑:

也是罗马人谈判中的一个幻灯片

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

int上的操作比enum上的操作快多了。

为自己判断。 每次你创build一个枚举你至less创build:

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

关于Service 。 在这个类中,标志主要用于比较,并将结果返回到上面的类( ContextWrapper )。 但基本上,如果你深入Android SDK的大肠, 你会发现自己几乎所有这些标志都习惯于平移操作

即使在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); 

所以原因是两个(至less):

  • 更less的内存消耗。

  • 加快按位操作。