1

使用enum类型时,您可以为每个常量添加参数,为每个常量提供一个主体,并为该类型提供一个主体。但如果你不这样做:

enum enumType { C1, C2, C3 };

使用enum类型是否与声明整数常量一样有效?

static final int C1 = 1;
static final int C2 = 2;
static final int C3 = 3;  // or whatever

还是由于此功能(提供主体的能力)仍然存在一些开销,即使在这种情况下未使用该功能?

4

4 回答 4

7

You didn't specify any kind of context within which the performance should be compared. In most cases the fact that enum members are objects is completely irrelevant because only the reference values are being compared; the objects themselves are not even touched.

However, public static final int are compile-time constants, and their values are hardcoded at the place of usage, which clearly imposes no overhead at all.

So it's very little overhead against no overhead at all, but at the expense of problems with compile-time constants, such that changing any of them requires recompiling everything which references it.

于 2013-08-05T19:27:56.220 回答
2

Yes, it's very efficient to use enums. You can even compare two instances of an enum using ==, with the added benefit of type safety:

Fruits.APPLES == Fruits.ORANGES

If you look inside the Enum class, you'll see that the equals() method uses == to compare two instances. And all the heavy lifting of creating enum instances is done at class compilation time, so there's no additional overhead there.

于 2013-08-05T19:27:53.637 回答
1

static final int与使用常量实现相关功能相比,枚举常量不会带来明显的性能损失。在内部,枚举常量简单地表示为 32 位整数。然而,在 JVM 的上下文中,枚举常量提供了类型安全性、可扩展性和远比使用 int 常量所能实现的灵活性。

使用 enum 常量而不是 int 常量的唯一缺点是加载和初始化 enum 类对象的时间,但是这在任何现实世界的场景中都不太可能明显。在您在问题中给出的示例中,一旦应用程序加载并运行,使用枚举而不是 int 常量不会有性能损失。还要注意,因为枚举常量必须是单例的(由 JVM 保证),它们可以有效地与 '==' 运算符进行相等性和身份比较,就像您对大多数原始值所做的那样。

Joshua Bloch 在 Effective Java 第 2 版中对枚举类型进行了精彩的讨论。并提出令人信服的论点,为什么应始终使用枚举常量来表示编译时已知的任何固定(甚至大部分固定)常量集。

于 2013-08-05T20:35:51.693 回答
0

这完全取决于使用它们的环境。好像你有一些相关的常量,那么你应该使用枚举,如果没有,那么你应该使用常量。因为将不相关的常量组合在一起是不合逻辑和错误的方式。

两者都是内联常量,即它们的每次出现都被替换为相应的值,因此无论何时对它们进行更改,都应该再次编译所有文件,这些文件在它们的代码中使用它们。否则你会得到不正确的结果。

如果您有相关的常量,那么使用枚举将是一个明智的选择。作为,

  1. 它们是序列化的。
  2. 提供了 API 支持,以便您可以有效地使用它们而无需太多开销。
于 2013-08-05T20:08:08.320 回答