Enums需要多少内存? [英] How much memory do Enums take?
问题描述
在Java中, 枚举
是一个完整的类:
Java编程语言枚举类型
比其他语言的
相当强大。
枚举声明定义一个类
(称为枚举类型)。枚举类
正文可以包括方法和其他
字段。
为了看到实际的大小每个枚举
,让我们做一个实际的枚举
并检查类的内容
它创建的文件。
假设我们有以下常量
枚举类:
public enum常量{
ONE,
TWO,
THREE;
}
编译上述枚举
并且使用 javap
导出的类类文件进行反汇编,给出以下内容:
pre>
从Constants.java编译
public final class Constants extends java.lang.Enum {
public static final Constants ONE;
public static final constants TWO;
public static final Constants THREE;
public static Constants [] values();
public static常量valueOf(java.lang.String);
static {};
}
反汇编显示枚举的每个字段
是常量
枚举
类的实例。 (使用 javap
的进一步分析将显示通过调用新的常量(String)
静态初始化块中的构造函数。)
因此,我们可以看出,我们创建的每个枚举
字段将会至少与在JVM中创建对象的开销一样多。
For example if I have an Enum with two cases, does it make take more memory than a boolean? Languages: Java, C++
In Java, an enum
is a full-blown class:
Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields.
In order to see the actual size of each enum
, let's make an actual enum
and examine the contents of the class
file it creates.
Let's say we have the following Constants
enum class:
public enum Constants {
ONE,
TWO,
THREE;
}
Compiling the above enum
and disassembling resulting class
file with javap
gives the following:
Compiled from "Constants.java"
public final class Constants extends java.lang.Enum{
public static final Constants ONE;
public static final Constants TWO;
public static final Constants THREE;
public static Constants[] values();
public static Constants valueOf(java.lang.String);
static {};
}
The disassembly shows that that each field of an enum
is an instance of the Constants
enum
class. (Further analysis with javap
will reveal that each field is initialized by creating a new object by calling the new Constants(String)
constructor in the static initialization block.)
Therefore, we can tell that each enum
field that we create will be at least as much as the overhead of creating an object in the JVM.
这篇关于Enums需要多少内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!