Avoid Enums

Avoid Enums

Enums are very convenient, but unfortunately can be painful when size and speed matter. For example, this:
public class Foo {
   public enum Shrubbery { GROUND, CRAWLING, HANGING }
}
turns into a 900 byte .class file (Foo$Shrubbery.class). On first use, the class initializer invokes the <init> method on objects representing each of the enumerated values. Each object gets its own static field, and the full set is stored in an array (a static field called "$VALUES"). That's a lot of code and data, just for three integers.
This:
Shrubbery shrub = Shrubbery.GROUND;
causes a static field lookup. If "GROUND" were a static final int, the compiler would treat it as a known constant and inline it.
The flip side, of course, is that with enums you get nicer APIs and some compile-time value checking. So, the usual trade-off applies: you should by all means use enums for public APIs, but try to avoid them when performance matters.
In some circumstances it can be helpful to get enum integer values through the ordinal() method. For example, replace:
for (int n = 0; n < list.size(); n++) {
    if (list.items[n].e == MyEnum.VAL_X)
       // do stuff 1
    else if (list.items[n].e == MyEnum.VAL_Y)
       // do stuff 2
}
with:
   int valX = MyEnum.VAL_X.ordinal();
   int valY = MyEnum.VAL_Y.ordinal();
   int count = list.size();
   MyItem items = list.items();

   for (int  n = 0; n < count; n++)
   {
        int  valItem = items[n].e.ordinal();

        if (valItem == valX)
          // do stuff 1
        else if (valItem == valY)
          // do stuff 2
   }
In some cases, this will be faster, though this is not guaranteed.

Comments

Popular posts from this blog

Android Objective type Question and Answers

Android Questions and Answers for written exams

SCJP1.6 Question and Answers