Enums需要多少内存? [英] How much memory do Enums take?

查看:107
本文介绍了Enums需要多少内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有一个枚举有两种情况,它是否需要比布尔值更多的内存?语言:Java,C ++

解决方案

在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屋!

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