比较Java数组和各种List的性能小结
内容摘要
话不多说,直接看示例代码
package cn.lion.test;
public class PerformanceTest {
privatestatic final int SIZE =100000;
publicstatic abstract class Test{
package cn.lion.test;
public class PerformanceTest {
privatestatic final int SIZE =100000;
publicstatic abstract class Test{
文章正文
话不多说,直接看示例代码
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能有所帮助。如果有疑问可以留言讨论。
代码注释