从文档中获取的信息:
枚举类型所需的内存通常是静态常量的两倍以上。在Android上应严格避免使用枚举。
http://developer.android.com/training/articles/memory.html#Overhead
编辑:
这也是Roman Guy演讲中的一张幻灯片:
操作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;
/**
* 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);
占用更少的内存。
由于位运算,工作速度更快。
enum
关键字其实是用来定义一个继承 java.lang.Enum
的普通类的语法糖。Enum
与其他静态类一样在永久代中具有相同的持久性。它们比整型常量使用更多的内存吗?当然是的,但是我们只是讨论几千字节的问题。为了那种微小的优化而牺牲类型安全、目的清晰和可维护性被广泛认为是不好的做法。 - Kevin Krumwiede正如其他答案所正确指出的那样,原因是枚举类型比 int 使用更多的内存。
为了理解这个决定的背景,您必须记住第一款 Android 设备只有 192MB 的 RAM。
正如Google 最接近官方声明的说法所解释的那样,枚举类型不仅是 int 的两倍大,而且当 dex 加载到 RAM 中时,它可能会是 int 的 13 倍。因此,框架团队非常谨慎地在这方面对其代码进行过度优化。如果在 Android 开发时有 4GB RAM 的设备,也许情况会不同,但我们永远不会知道。
非框架开发的建议是根据自己的用例做出判断。请记住,Proguard 通常会将您的枚举类型转换为 int。
int
相比,使用enum
会有更多的内存开销。 - tyczj