我试图通过将 int 原语更改为 short 来优化 Android 游戏的 RAM 使用。在我这样做之前,我对 Java 中原始类型的性能很感兴趣。
所以我使用 caliper 库创建了这个小测试基准。
public class BenchmarkTypes extends Benchmark {
@Param("10") private long testLong;
@Param("10") private int testInt;
@Param("10") private short testShort;
@Param("5000") private long resultLong = 5000;
@Param("5000") private int resultInt = 5000;
@Param("5000") private short resultShort = 5000;
@Override
protected void setUp() throws Exception {
Random rand = new Random();
testShort = (short) rand.nextInt(1000);
testInt = (int) testShort;
testLong = (long) testShort;
}
public long timeLong(int reps){
for(int i = 0; i < reps; i++){
resultLong += testLong;
resultLong -= testLong;
}
return resultLong;
}
public int timeInt(int reps){
for(int i = 0; i < reps; i++){
resultInt += testInt;
resultInt -= testInt;
}
return resultInt;
}
public short timeShort(int reps){
for(int i = 0; i < reps; i++){
resultShort += testShort;
resultShort -= testShort;
}
return resultShort;
}
}
测试的结果让我吃惊。
测试环境
在 Caliper 库下运行基准测试。
测试结果
https://microbenchmarks.appspot.com/runs/0c9bd212-feeb-4f8f-896c-e027b85dfe3b
诠释 2.365 纳秒
长 2.436 ns
短 8.156 ns
测试结论?
short 原始类型比 long 和 int 原始类型明显慢(3-4~ 倍)?
问题
为什么 short 原语比 int 或 long 慢得多?我希望 int 原始类型在 32 位 VM 上最快,并且 long 和 short 在时间上相等,或者 short 更快。
Android手机也是这样吗?知道 Android 手机通常在 32 位环境中运行,现在越来越多的手机开始配备 64 位处理器。