阅读Android我可以看到框架的许多部分使用int
常量作为返回值,或配置值(like in here中的START_REDELIVER_INTENT
),而不是enum
,据我所知,这是一个更好的选择,因为很多原因可以是在网上发现,like this。
所以这让我想知道......为什么谷歌决定使用这么多的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
编辑:
也是罗曼盖伊谈话之一的幻灯片
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.)
关于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);
正如其他一些答案正确陈述,其原因是因为枚举使用的内存多于int。
为了给出该决定的背景,你必须记住first Android device had 192mb of RAM。
正如在closest thing to an official statement from Google中所解释的,枚举不仅仅是int的2倍,但是当dex被加载到RAM中时,它的大小可能是13倍。因此,框架团队非常小心地在这方面过早地优化他们的代码。如果Android开发时有4GB内存的设备,也许这会有所不同,但我们永远不会知道。
非框架开发的建议是对您自己的用例做出判断。记住,Proguard通常会将你的枚举转换为整数,这绝对不会让人痛苦。