为什么不使用Android的更枚举?Android

2023-09-12 07:03:33 作者:ヾnight、晴

我开始真的很喜欢用我的code C#和Java枚举有以下几个原因:

I've started to really like using C# and Java enums in my code for several reasons:

他们更类型安全的不是整数的布尔标志,字符串或集。 他们带来更具可读性code。 这是比较难以枚举设置为无效值比int或字符串。 他们可以很容易地发现了允许值的变量或参数。 在我读过的一切表明,他们的表现一样好,在C#中的整数和大多数JVM 。

然而,Android的框架有很多情况下,需要不同类型的标志传来传去,但他们都不使用枚举。一对夫妇的例子,我觉得它们的使用将是有益的 Toast.LENGTH_SHORT / Toast.LENGTH_LONG View.GONE View.VISIBLE 等。

However, the Android framework has numerous cases where flags of various types need to be passed around, but none of them seem to use enums. A couple of examples where I would think their use would be beneficial are Toast.LENGTH_SHORT / Toast.LENGTH_LONG and View.GONE, View.VISIBLE, etc.

这是为什么?不要枚举比的Dalvik简单的整数值表现较差?有一些其他的缺点我不知道呢?

Why is this? Do enums perform worse than simple integer values in Dalvik? Is there some other drawback I'm not aware of?

推荐答案

这个答案是过时的2011年3月。

枚举可用于升级Froyo和最多 - 按照这个答案(为什么避免枚举如果你只需要整型调离Android的性能提示?)从Android虚拟团队的成员(并他的博客)

Enums can be used on Froyo and up - according to this answer (Why was "Avoid Enums Where You Only Need Ints" removed from Android's performance tips?) from a member of the Android VM team (and his blog).

官方Android团队的建议是为了避免枚举,只要你能避免它:

The official Android team recommendation is to avoid enums whenever you can avoid it:

枚举是很方便,但   遗憾的是,当尺寸是痛苦的   和速度问题。例如,这

Enums are very convenient, but unfortunately can be painful when size and speed matter. For example, this:

public enum Shrubbery { GROUND, CRAWLING, HANGING }

     

增加740个字节   相比于您的.dex文件   等价类有三个公开   静态最终整数。在第一次使用时,   类初始化调用   对物体的方法重新presenting每   枚举值。每个对象   获得其自己的静态字段和   全套被存储在一个阵列(一   静态字段名为$ VALUES)。这是   很多code和数据,只是三   整数。此外,这样的:

adds 740 bytes to your .dex file compared to the equivalent class with three public static final ints. On first use, the class initializer invokes the method on objects representing each of the enumerated values. Each object gets its own static field, and the full set is stored in an array (a static field called "$VALUES"). That's a lot of code and data, just for three integers. Additionally, this:

Shrubbery shrub = Shrubbery.GROUND;

     

使静态字段查找。如果   地是一个静态的最终诠释,在   编译器把它当作一个已知   常数和内联了。

causes a static field lookup. If "GROUND" were a static final int, the compiler would treat it as a known constant and inline it.

来源:避免枚举如果你只需要整型