And*_*niy 6 java performance arraylist
我有点困惑.在填充循环的第一次迭代中,我在使用initial capacityfor ArrayListvs而不使用初始容量时看到填充时间的一些回归.
根据常识和这个问题:为什么要启动具有初始容量的ArrayList?
它必须完全相反.
它不是很好的基准测试,我想知道:为什么在第一次迭代时它总是在使用初始容量时消耗更多的时间和CPU ArrayList?
这是测试:
public class TestListGen {
public static final int TEST = 100_000_000;
public static void main(String[] args) {
test(false);
}
private static void test(boolean withInitCapacity) {
System.out.println("Init with capacity? " + withInitCapacity);
for (int i = 0; i < 5; i++)
av += fillAndTest(TEST, withInitCapacity ? new ArrayList<Integer>(TEST) : new ArrayList<Integer>());
System.out.println("Average: " + (av / 5));
}
private static long fillAndTest(int capacity, List<Integer> list) {
long time1 = System.nanoTime();
for (int i = 0; i < capacity; i++) list.add(i);
long delta = System.nanoTime() - time1;
System.out.println(delta);
return delta;
}
}
Run Code Online (Sandbox Code Playgroud)
输出:1)
Init with capacity? false
17571882469
12179868327
18460127904
5894883202
13223941250
Average: 13466140630
Run Code Online (Sandbox Code Playgroud)
2)
Init with capacity? true
37271627087
16341545990
19973801769
4888093008
2442179779
Average: 16183449526
Run Code Online (Sandbox Code Playgroud)
我测试过它:JDK 1.7.0.40,JDK 1.8.0.31
这是一个 Java 堆分配工件,导致了您意想不到的结果。调整初始堆分配,通过从混合中删除堆分配时间,您将看到更一致的结果。另外,您需要确保运行基准测试的进程没有被交换。在我的系统上,我遇到了 OOM 错误,TEST = 100_000_000并且必须将其减少到10_000_000我的测试中。我也跑了两个test(false),test(true)一个接一个。请注意在启动时分配堆并在下面的结果中添加显式 gc 如何使各个时间更加一致。添加热身对于使测试更加一致也很重要,但我并没有为此烦恼。
原始测试
Init with capacity? false
1714537208
1259523722
1215986030
1098740959
1029914697
Average: 1263740523
Init with capacity? true
343100302
612709138
355210333
603609642
348401796
Average: 452606242
Run Code Online (Sandbox Code Playgroud)
测试用-Xms500m -Xmx500m
Init with capacity? false
682827716
738137558
576581143
662777089
555706338
Average: 643205968
Init with capacity? true
368245589
312674836
297705054
392935762
307209139
Average: 335754076
Run Code Online (Sandbox Code Playgroud)
之前用-Xms500m -Xmx500m+测试System.gc()fillAndTest()
Init with capacity? false
502767979
435508363
420956590
487184801
416041923
Average: 452491931
Init with capacity? true
300744404
298446734
299080656
300084036
298473576
Average: 299365881
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
143 次 |
| 最近记录: |