为什么Android不使用更多的枚举? [英] Why doesn't Android use more enums?

查看:20
本文介绍了为什么Android不使用更多的枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于以下几个原因,我开始非常喜欢在代码中使用 C# 和 Java 枚举:

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

  • 与整数、字符串或布尔标志集相比,它们的类型安全得多.
  • 它们导致代码更具可读性.
  • 将枚举设置为无效值比将整数或字符串设置为无效值更困难.
  • 它们可以轻松地发现变量或参数的允许值.
  • 我所读到的一切都表明它们在 C# 和大多数 JVM 中的性能与整数一样好.

然而,Android 框架有很多情况需要传递各种类型的标志,但似乎没有一个使用枚举.我认为使用它们会有好处的几个例子是 Toast.LENGTH_SHORT/Toast.LENGTH_LONGView.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 VM 团队成员(以及 他的博客).

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 文件与具有三个公共的等效类静态最终整数.首次使用时,类初始化器调用表示每个对象的方法枚举值.每个对象获得自己的静态字段,并且完整的集合存储在一个数组中(一个名为$VALUES"的静态字段).那是大量代码和数据,只为三个整数.此外,这:

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;

导致静态字段查找.如果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.

来源:避免只需要整数的枚举

这篇关于为什么Android不使用更多的枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆