测试ArrayList和LinkedList性能

测试ArrayList和LinkedList性能的案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Random;
/**
* Created by gene on 2017/4/23.
*/
public class Test {
public static void main(String[] args) {
ArrayList arraylist = new ArrayList();
ArrayList bigarraylist = new ArrayList(5000000);
LinkedList linkedlist = new LinkedList();
Object obj = new Object();
/**
* 测试ArrayList和LinkedList在末尾插入的性能
*/
long start = System.currentTimeMillis();
for (int i = 0; i < 5000000; i++) {
arraylist.add(obj);
}
long end = System.currentTimeMillis();
System.out.println("ArrayList插入用时:" + (end - start));
start=System.currentTimeMillis();
for (int i = 0; i < 5000000; i++) {
linkedlist.add(obj);
}
end = System.currentTimeMillis();
System.out.println("LinkedList插入用时:" + (end - start));
start = System.currentTimeMillis();
for (int i = 0; i < 5000000; i++) {
bigarraylist.add(obj);
}
end = System.currentTimeMillis();
System.out.println("调整初始容量的arrayList插入用时:" + (end - start));
/**
* 测试ArrayList和LinkedList随机插入的性能
*/
Random r1 = new Random();
Random r2 = new Random();
start = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
arraylist.add(r1.nextInt(1000), obj);
}
end = System.currentTimeMillis();
System.out.println("ArrayList随机插入用时:" + (end - start));
LinkedHashMap map = new LinkedHashMap();
map.put(1, 1);
map.put(2, 2);
start = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
linkedlist.add(r2.nextInt(1000), obj);
}
end = System.currentTimeMillis();
System.out.println("LinkedList随机插入用时:" + (end - start));
/**
* 测试ArrayList和LinkedList的删除性能
*/
start = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
arraylist.remove(250000);
}
end = System.currentTimeMillis();
System.out.println("ArrayList删除用时:" + (end - start));
start = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
linkedlist.remove(250000);
}
end = System.currentTimeMillis();
System.out.println("LinkedList删除用时:" + (end - start));
}
}