在微基准测试中,是的,检查整数常量相等将比检查枚举常量相等更快.
然而,在实际的应用中,更不用说游戏,这完全是无关紧要的. AWT子系统(或任何其他GUI工具包)中发生的事情将这些微观性能考虑因素降低许多数量级.
编辑
让我详细说一下吧.
枚举比较如下:
aload_0
getstatic
if_acmpne
一个小整数的整数比较如下所示:
iload_0
iconst_1
if_icmpne
显然,第一个比第二个更多的工作,虽然差别很小.
运行以下测试用例:
class Test {
static final int ONE = 1;
static final int TWO = 2;
enum TestEnum {ONE, TWO}
public static void main(String[] args) {
testEnum();
testInteger();
time("enum", new Runnable() {
public void run() {
testEnum();
}
});
time("integer", new Runnable() {
public void run() {
testInteger();
}
});
}
private static void testEnum() {
TestEnum value = TestEnum.ONE;
for (int i = 0; i < 1000000000; i++) {
if (value == TestEnum.TWO) {
System.err.println("impossible");
}
}
}
private static void testInteger() {
int value = ONE;
for (int i = 0; i < 1000000000; i++) {
if (value == TWO) {
System.err.println("impossible");
}
}
}
private static void time(String name, Runnable runnable) {
long startTime = System.currentTimeMillis();
runnable.run();
System.err.println(name + ": " + (System.currentTimeMillis() - startTime) + " ms");
}
}
而你会发现枚举比较慢,整数比较,在我的机器上大约1.5%.
我所说的是,这种差异在真正的应用中并不重要(“过早优化是所有邪恶的根源”).我在专业的基础上处理性能问题(参见我的个人资料),我从来没有看到可以追溯到这样的热点.