为什么 Android 不使用更多的枚举?
我开始非常喜欢在代码中使用 C# 和 Java 枚举,原因如下:
- 它们比整数、字符串或布尔标志集更加类型安全。
- 它们会产生更具可读性的代码。
- 将枚举设置为无效值比 int 或字符串更困难。
- 它们可以轻松发现变量或参数的允许值。
- 我读到的所有内容都表明它们在 C# 和大多数 JVM 中的性能与整数一样好。
然而,Android框架有很多需要传递各种类型标志的情况,但它们似乎都没有使用枚举。我认为使用它们会有所帮助的几个示例是 Toast.LENGTH_SHORT
/ Toast.LENGTH_LONG
和 View.GONE
、View.VISIBLE
等
这是为什么呢? Dalvik 中枚举的性能是否比简单整数值差?还有其他我不知道的缺点吗?
I've started to really like using C# and Java enums in my code for several reasons:
- They are much more type-safe than integers, strings, or sets of boolean flags.
- They lead to more readable code.
- It's more difficult to set an enum to an invalid value than an int or string.
- They make it easy to discover the allowed values for a variable or parameter.
- Everything I've read indicates that they perform just as well as integers in C# and most JVMs.
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.
Why is this? Do enums perform worse than simple integer values in Dalvik? Is there some other drawback I'm not aware of?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
此答案自 2011 年 3 月起已过时。
根据此答案,枚举可以在 Froyo 及更高版本上使用(为什么从 Android 性能提示中删除了“只需要整数时避免枚举”?)来自 Android VM 团队的成员(以及 他的博客)。
上一个答案:
官方 Android 团队建议尽可能避免枚举:
来源:在只需要整数的地方避免使用枚举
This answer is out of date as of March 2011.
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).
Previous Answer:
The official Android team recommendation is to avoid enums whenever you can avoid it:
Source: Avoid Enums Where You Only Need Ints
整数更小,需要的开销也更少,这在移动设备上仍然很重要。
Integers are smaller, and require less overhead, something that still matters on mobile devices.
我的一位同事针对这种情况做了一个小测试。他自动生成了一个
class
和一个具有相同数量“enum”的enum
。我相信他生成了 30000 个条目。结果是:
class
的.class
大约为 1200KBenum
的.class
大约为 800KB希望这个帮助某人。
A colleague of mine performed a small test regarding this situation. He auto generated a
class
and anenum
with the same amount of "enums". I believe he generated 30000 entries.The results were:
.class
for theclass
was roughly 1200KB.class
for theenum
was roughly 800KBHope this helps someone.