浏览 4142 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2010-03-01
最后修改:2010-03-02
/** * 测试 对于ArrayList的iterator遍历和for遍历的效率问题 * 注: 这个测试结果对其他容器类不一定成立 比如LinkedList * */ public class IteratorTest { static int size = 1000000; static List<Object> list1 = new ArrayList<Object>(); static List<Object> list2 = new ArrayList<Object>(); static { for (int i = 0; i < size; i++) { list1.add(new Object()); list2.add(new Object()); } } @Test public void iteratorTest() { long start = System.currentTimeMillis(); for (Iterator<Object> iterator = list1.iterator(); iterator.hasNext();) { Object entry = (Object) iterator.next(); // System.out.print(entry); } System.out.println("\niterator " + (System.currentTimeMillis() - start) + " ms"); } @Test(dependsOnMethods = "iteratorTest") public void forTest() { long start = System.currentTimeMillis(); for (int i = 0, size = list2.size(); i < size; i++) {//这里是一次性求出size() ,假如在遍历的过程中list的内容有增减的话,遍历逻辑会出错 Object entry = list2.get(i); // System.out.print(entry); } System.out.println("\nfor " + (System.currentTimeMillis() - start) + " ms"); } @Test(groups="alone",invocationCount=10) //testng 测试10次 public void compareTest() { long start = System.currentTimeMillis(); for (Iterator<Object> iterator = list1.iterator(); iterator.hasNext();) { Object entry = (Object) iterator.next(); // System.out.print(entry); } long time=System.currentTimeMillis()-start; start = System.currentTimeMillis(); for (int i = 0, size = list2.size(); i < size; i++) { Object entry = list2.get(i); // System.out.print(entry); } long time2=System.currentTimeMillis() - start; System.out.println("iterator "+time +" ms, for "+time2+" ms"); } }
输出 iterator 32 ms for 15 ms iterator 32 ms, for 15 ms iterator 31 ms, for 0 ms iterator 31 ms, for 0 ms iterator 32 ms, for 15 ms iterator 31 ms, for 16 ms iterator 31 ms, for 16 ms iterator 31 ms, for 0 ms iterator 31 ms, for 0 ms iterator 31 ms, for 16 ms iterator 31 ms, for 16 ms
遍历中的remove测试 @Test public void iteratorTest() { long start = System.currentTimeMillis(); for (Iterator<Object> iterator = list1.iterator(); iterator.hasNext();) { Object entry = (Object) iterator.next(); System.out.println(entry); iterator.remove();//right } System.out.println("\niterator " + (System.currentTimeMillis() - start) + " ms"); } @Test(expectedExceptions = IndexOutOfBoundsException.class) public void forTest() { long start = System.currentTimeMillis(); for (int i = 0, size = list2.size(); i < size; i++) { Object entry = list2.get(i); System.out.println(entry); list2.remove(i);//wrong } System.out.println("\nfor " + (System.currentTimeMillis() - start) + " ms"); }
输出 0 1 2 3 4 5 6 7 8 9 iterator 0 ms 0 2 4 6 8
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2010-06-01
这是java对iterator设定的一种机制!!
list2.remove(i);//wrong |
|
返回顶楼 | |