以下程序分别对Java数组、ArrayList、LinkedList和Vector进行随机访问和迭代等操作,并比较这种集合的性能。
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类在各方面没有突出的性能,且此类已不提倡使用了。