gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:10:29 26 4
gpt4 key购买 nike

我开始真正喜欢在我的代码中使用 C# 和 Java 枚举有几个原因:

  • 它们比整数、字符串或 bool 标志集更安全。
  • 它们会带来更易读的代码。
  • 将枚举设置为无效值比 int 或字符串更难。
  • 它们使发现变量或参数的允许值变得容易。
  • 我读过的所有内容都表明它们在 C# 和大多数 JVM 中的性能与整数一样好。

然而,Android 框架有很多情况需要传递各种类型的标志,但似乎没有一个使用枚举。我认为使用它们会有好处的几个例子是 Toast.LENGTH_SHORT/Toast.LENGTH_LONGView.GONE, View.VISIBLE

这是为什么?枚举在 Dalvik 中的性能是否比简单的整数值差?还有其他一些我不知道的缺点吗?

最佳答案

截至 2011 年 3 月,此答案已过期。

枚举可用于 Froyo 及更高版本 - 根据 Android VM 团队成员(和 Why was “Avoid Enums Where You Only Need Ints” removed from Android's performance tips?)的此答案 (his blog)。


上一个答案:

Android 官方团队建议尽可能避免枚举:

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

public enum Shrubbery { GROUND, CRAWLING, HANGING }

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.

来源:Avoid Enums Where You Only Need Ints

关于android - 为什么 Android 不使用更多的枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4822877/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com