dev*_*ium 18 java performance enums
我正在实施一个2人游戏,它将在紧密的循环中运行数十万次,然后是性能至关重要.
我的代码实际上看起来像这样:
public class Table {
private final int WHITE_PLAYER = +1;
private final int BLACK_PLAYER = -1;
private final int currentPlayer;
private final int otherPlayer;
...
}
Run Code Online (Sandbox Code Playgroud)
我想知道如果我选择更换会有任何性能损失
private final int WHITE_PLAYER = +1;
private final int BLACK_PLAYER = -1;
Run Code Online (Sandbox Code Playgroud)
枚举定义为
public enum Players {
WhitePlayer,
BlackPlayer
}
Run Code Online (Sandbox Code Playgroud)
我认为枚举只是整数常量的语法糖,并且对于测试枚举生成的字节码以及调用它的代码进行釉面查看,似乎表明使用它们确实与制作静态相同方法调用,但是对于在首次运行时设置的某些枚举基础结构.
我的假设是,确实使用枚举作为静态常量是正确的还是我错过了什么?
Ing*_*gel 24
在微基准测试中,是的,检查整数常量相等将比检查枚举常量相等更快.
但是,在实际应用中,更不用说游戏,这将完全无关紧要.AWT子系统(或任何其他GUI工具包)中发生的事情使这些微观性能考虑因素大不相同.
编辑
让我详细说明一下.
枚举比较如下:
aload_0
getstatic
if_acmpne
Run Code Online (Sandbox Code Playgroud)
小整数的整数比较如下:
iload_0
iconst_1
if_icmpne
Run Code Online (Sandbox Code Playgroud)
显然,第一个比第二个更多的工作,虽然差异很小.
运行以下测试用例:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
你会发现枚举比较慢于整数比较,在我的机器上大约1.5%.
我所说的只是这种差异在实际应用中无关紧要("过早优化是万恶之源").我在专业的基础上处理性能问题(参见我的个人资料),我从未见过可以追溯到这样的事情的热点.
unb*_*eli 11
在关心性能之前,您应该关心拥有漂亮且可读的代码.直到你的分析结果(没有猜测!)表明枚举是瓶颈,忘记性能并使用更容易理解的东西.
| 归档时间: |
|
| 查看次数: |
11589 次 |
| 最近记录: |