Why doesn't Android use more enums?
AndroidEnumsAndroid Problem Overview
I've started to really like using C# and Java enums in my code for several reasons:
- They are much more type-safe than integers, strings, or sets of boolean flags.
- They lead to more readable code.
- It's more difficult to set an enum to an invalid value than an int or string.
- They make it easy to discover the allowed values for a variable or parameter.
- Everything I've read indicates that they perform just as well as integers in C# and most JVMs.
However, the Android framework has numerous cases where flags of various types need to be passed around, but none of them seem to use enums. A couple of examples where I would think their use would be beneficial are Toast.LENGTH_SHORT
/ Toast.LENGTH_LONG
and View.GONE
, View.VISIBLE
, etc.
Why is this? Do enums perform worse than simple integer values in Dalvik? Is there some other drawback I'm not aware of?
Android Solutions
Solution 1 - Android
This answer is out of date as of March 2011.
Enums can be used on Froyo and up - according to this answer (Why was “Avoid Enums Where You Only Need Ints” removed from Android's performance tips?) from a member of the Android VM team (and his blog).
Previous Answer:
The official Android team recommendation is to avoid enums whenever you can avoid it:
> Enums are very convenient, but > unfortunately can be painful when size > and speed matter. For example, this: > public enum Shrubbery { GROUND, CRAWLING, HANGING }
> adds 740 bytes to
> your .dex file compared to the
> equivalent class with three public
> static final ints. On first use, the
> class initializer invokes the
Solution 2 - Android
Integers are smaller, and require less overhead, something that still matters on mobile devices.
Solution 3 - Android
A colleague of mine performed a small test regarding this situation. He auto generated a
class
and an enum
with the same amount of "enums". I believe he generated 30000 entries.
The results were:
.class
for theclass
was roughly 1200KB.class
for theenum
was roughly 800KB
Hope this helps someone.