Showing posts with label Enum. Show all posts
Showing posts with label Enum. Show all posts

Monday, 27 January 2014

How much memory do Enums take?

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 {
Compiling the above enum and disassembling resulting class file with javap gives the following:
Compiled from ""
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.