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

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

问题描述

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

解决方案

在Java中, 枚举是一个完整的类



< blockquote>

Java编程语言枚举类型
比其他语言的
类型强大得多。
枚举声明定义了一个类
(称为枚举类型)。枚举类
body可以包含方法和其他
字段。


为了看到实际大小每个枚举,让我们做一个实际的枚举并检查类的内容常量枚举类:

  public enum常量{
ONE,
TWO,
THREE;
}

编译上述枚举并使用 javap 反汇编 class 文件,得到以下结果:

 从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 {};
}

反汇编显示枚举的每个字段常量 枚举类的实例。 (使用 javap 的进一步分析将揭示每个字段是通过创建一个新对象初始化的,通过调用 new Constants(String)



因此,我们可以知道我们创建的每个 enum 字段至少与在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.

这篇关于枚举需要多少内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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