我尝试通过将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
Int 2.365 ns
长2.436 ns
短8.156 ns
测试结论?
短基元类型比long和int基元类型慢得多(3-4~)?
题
>为什么短原语明显慢于int或long?我希望int原语类型在32位虚拟机上最快,长短在时间上相等,或者短到甚至更快.
> Android手机也是如此吗?知道Android手机通常在32位环境中运行,现在越来越多的手机开始配备64位处理器.
解决方法
Java字节代码不支持小于int的基本类型的基本操作(,–,*,/,>>,>>>,<<,%).在指令集中没有为这种操作分配字节代码.因此,VM需要将short(s)转换为int(s),执行操作,然后将int截断为short并将其存储在结果中. 使用javap检查生成的字节代码,以查看short和int测试之间的区别. VM / JIT优化显然偏向于int / long操作,这是有意义的,因为它们是最常见的. 小于int的类型有其用途,但主要用于在数组中保存内存.它们不像简单的类成员那样适合(当然,当它适用于数据类型时,你仍然会使用它们).较小的成员甚至可能不会减小对象大小.当前VM(再次)主要针对执行速度而定制,因此VM甚至可以将字段与本机机器字边界对齐以提高访问性能,但代价是内存花费.