How much memory do Enums take?

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.


In Java, there should only be one instance of each of the values of your enum in memory. A reference to the enum then requires only the storage for that reference. Checking the value of an enum is as efficient as any other reference comparison.


You would only worry about this when storing large quantities of enums. For Java, you may be able to use an EnumSet in some cases. It uses a bit vector internally which is very space efficient and fast.

http://java.sun.com/j2se/1.5.0/docs/api/java/util/EnumSet.html