话不多说,直接看示例代码
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
package cn.lion.test;
public class PerformanceTest {
privatestatic final int SIZE = 100000 ;
publicstatic abstract class Test{
privateString operation;
publicTest(String operation){
this .operation= operation;
}
publicabstract void test(List<String> list);
publicString getOperation(){
returnoperation;
}
}
//执行迭代操作的匿名类
staticTest iterateTest = new Test( "iterate" ){
publicvoid test(List<String> list){
for (inti= 0 ; i< 10 ; i++){
Iterator<String>it = list.iterator();
while (it.hasNext()){
it.next();
}
}
}
};
//执行随机访问的匿名类
staticTest getTest = new Test( "get" ){
publicvoid test(List<String> list){
for (inti= 0 ; i<list.size(); i++){
for (intk= 0 ; k< 10 ; k++){
list.get(k);
}
}
}
};
//执行插入的匿名类
staticTest insertTest = new Test( "insert" ){
publicvoid test(List<String> list){
ListIterator<String>it = list.listIterator(list.size()/ 2 );
for (inti= 0 ; i<SIZE; i++){
it.add( "lion" );
}
}
};
//执行删除的匿名类
staticTest removeTest = new Test( "remove" ){
publicvoid test(List<String> list){
ListIterator<String>it = list.listIterator();
while (it.hasNext()){
it.next();
it.remove();
}
}
};
staticpublic void testArray(List<String> list){
Test[]tests = {iterateTest, getTest};
test(tests,list);
}
staticpublic void testList(List<String> list){
Test[]tests = {insertTest, iterateTest, getTest, removeTest};
test(tests,list);
}
staticpublic void test(Test[] tests, List<String> list){
for (inti= 0 ; i<tests.length; i++){
System.out.print(tests[i].getOperation()+ "操作:" );
longt1 = System.currentTimeMillis();
tests[i].test(list);
longt2 = System.currentTimeMillis();
System.out.print(t2-t1+ "ms" );
System.out.println();
}
}
publicstatic void main(String[] args){
List<String>list = null ;
//测试数组的迭代和随机访问操作
System.out.println( "------测试数组------" );
String[]tstr = new String[SIZE];
Arrays.fill(tstr, "lion" );
list= Arrays.asList(tstr);
testArray(list);
tstr= new String[SIZE/ 2 ];
Collection<String>coll = Arrays.asList(tstr);
//测试Vector
System.out.println( "------测试Vector------" );
list= new Vector<String>();
list.addAll(coll);
testList(list);
//测试LinkedList
System.out.println( "------测试LinkedList------" );
list= new LinkedList<String>();
list.addAll(coll);
testList(list);
//测试ArrayList
System.out.println( "------测试Vector------" );
list= new ArrayList<String>();
list.addAll(coll);
testList(list);
}
}
|
运行结果如图
从结果可以看出,对数组进行随机访问和迭代操作的速度是最快的;对LinkedList进行插入和删除操作的速度是最快的;对ArrayList进行随机访问的速度也很快;Vector类在各方面没有突出的性能,且此类已不提倡使用了。
总结
以上就是本文的全部内容,希望对大家学习或者使用Java能有所帮助。如果有疑问可以留言讨论。