java2d 性能,java - 2D数组分配的性能 - SO中文参考 - www.soinside.com

[我想知道为什么立即分配2D int数组(new int[50][2])比单独分配要差,也就是说,先执行new int[50][],然后依次执行new int[2]。这是一个非专业的基准代码:public class AllocationSpeed {

private static final int ITERATION_COUNT = 1000000;

public static void main(String[] args) {

new AllocationSpeed().run();

}

private void run() {

measureSeparateAllocation();

measureAllocationAtOnce();

}

private void measureAllocationAtOnce() {

Stopwatch stopwatch = Stopwatch.createStarted();

for (int i = 0; i < ITERATION_COUNT; i++) {

allocateAtOnce();

}

stopwatch.stop();

System.out.println("Allocate at once: " + stopwatch);

}

private int allocateAtOnce() {

int[][] array = new int[50][2];

return array[10][1];

}

private void measureSeparateAllocation() {

Stopwatch stopwatch = Stopwatch.createStarted();

for (int i = 0; i < ITERATION_COUNT; i++) {

allocateSeparately();

}

stopwatch.stop();

System.out.println("Separate allocation: " + stopwatch);

}

private int allocateSeparately() {

int[][] array = new int[50][];

for (int i = 0; i < array.length; i++) {

array[i] = new int[2];

}

return array[10][1];

}

}

我在64位Linux上进行了测试,这些是使用不同64位oracle Java版本的结果:

1.6.0_45-b06:Separate allocation: 401.0 ms

Allocate at once: 1.673 s

1.7.0_45-b18Separate allocation: 408.7 ms

Allocate at once: 1.448 s

1.8.0-ea-b115Separate allocation: 380.0 ms

Allocate at once: 1.251 s

出于好奇,我也使用OpenJDK 7进行了尝试(差异较小):Separate allocation: 424.3 ms

Allocate at once: 1.072 s

对我来说,这很违反直觉,我希望一次分配会更快。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值