【发布时间】:2014-06-19 10:31:18
【问题描述】:
我尝试通过将 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 纳秒
8.156 ns 短
测试结论?
short 原始类型比 long 和 int 原始类型慢得多(3-4~ 倍)?
问题
为什么 short 原语明显比 int 或 long 慢?我希望 int 原始类型在 32 位 VM 上是最快的,并且 long 和 short 在时间上相等,或者 short 更快。
Android 手机也是这样吗?知道 Android 手机通常在 32 位环境中运行,现在越来越多的手机开始配备 64 位处理器。
【问题讨论】:
-
您还没有预热 JIT。你没有做足够的迭代。这不是您对 Java 进行微基准测试的方式。
-
它(很可能)是由 Java 将 short(每次)转换为 int(或 long)以进行算术运算
-
@GermannArlington - 不。对 1000 倍时间差异的真正解释是基准编写不正确。请参阅链接的问答。
-
没错,这里没有真正的基准!但是慢 1000 倍?创建一个好的基准真的会有这么大的不同吗?
-
使用 java caliper 库用新的测试结果更新了问题。
标签: java android performance caliper