NameSpace NameSpace - 1 year ago 76
Android Question

Enum vs. Static Constants, memory footprint

First see the following quote from the Android developer's guide:

Despite the ominous warning in the first bullet point to "strictly avoid using enums on Android," what is said under that point actually doesn't sound so bad. Constants are 32 bit integers, and enums are likely 64 bit references. The math given there about enums being twice as expensive makes sense, and doesn't seem so scary.

My concern is that the warning, might in part, be based off the second bullet point.

I am wondering whether a simple enum "class" declaration carries 500 byte overhead? How about eacn enum type?

It seems quite plausible that types could be "extended classes" since they can take their own methods, rather than just instances. To phrase it as a question, if my enum is Color, and I have 20 Color enum types (e.g. red, blue, green...), is that 500 bytes per type?

Answer Source

Enums are an ongoing infinite debate in the Android world.

You can hear a good talk from Romain Guy and Chet Haase about it here:

According to this video how big is an object in Dalvik can be calculated as:

overhead of Object + overhead of dlmalloc + data + align
  • The overhead of an Object is exactly 8 bytes.
  • The overhead of dlmalloc can be 4 - 8 bytes (most of the times is 8 bytes)
  • The size of the data depends on the data (of course)
  • Finally everything must be 8-byte aligned (for example, if you have 12 bytes for an Object this will take 16 bytes)

Remember to keep in mind that every value of an enum is actually an instance of an Enum class.

Another important point to keep in mind is the dex file size. For example, the following enum will take around 1,112 bytes

public static enum Things {

Or you can have two static int which will take 128 bytes.

public static int THING_1 = 1;
public static int THING_2 = 2;

You have 10x improvement in the dex file size.

There is also a big different in on how much compiled dalvik code is generated. For Enum there is a lot of stuff the compiler does for you. There is a static class initialization the first time the class is loaded at runtime. It adds overtime at start-up.

On the other hand enum bring also a lot of pros: readability, usability, type safe code. I would worry about enum only in particular extreme cases.

Especially when we consider that using ProGuard can optimize Enums converting them to normal int constants.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download