大伙都知道Java 5加入了枚举类型, 定义和使用起来十分方便, 例如:

public enum Weekdays
{
  MON,

  TUE,
  WED,
  THU,
  FRI,
  SAT,
  SUN;
}

但是效率如何呢? 不客气的说, 很差! 使用JAD反编译之后, 却让人大跌眼镜, 毫无疑问, 稍微有点数据结构常识的人都会看出问题所在:



// Source File Name:   Weekdays.java


package enumtest;




public final class Weekdays extends Enum
{


public static final Weekdays MON;
public static final Weekdays TUE;
public static final Weekdays WED;
public static final Weekdays THU;
public static final Weekdays FRI;
public static final Weekdays SAT;
public static final Weekdays SUN;
private static final Weekdays ENUM$VALUES[];


private Weekdays(String s, int i)
{
super(s, i);
}


public static Weekdays[] values()
{
Weekdays aweekdays[];
int i;
Weekdays aweekdays1[];
System.arraycopy(aweekdays = ENUM$VALUES, 0, aweekdays1 = new Weekdays[i = aweekdays.length], 0, i);
return aweekdays1;
}


public static Weekdays valueOf(String s)
{
return (Weekdays)Enum.valueOf(enumtest/Weekdays, s);
}


static
{
MON = new Weekdays("MON", 0);
TUE = new Weekdays("TUE", 1);
WED = new Weekdays("WED", 2);
THU = new Weekdays("THU", 3);
FRI = new Weekdays("FRI", 4);
SAT = new Weekdays("SAT", 5);
SUN = new Weekdays("SUN", 6);
ENUM$VALUES = (new Weekdays[] {
MON, TUE, WED, THU, FRI, SAT, SUN
});
}
}

转载请注明:WebLogic Android 博客 » Java枚举类型-最低效的常量定义方式之一