
如果你只是在集合上徘徊以读取所有值,那么使用迭代器或新的for循环语法之间就没有区别,因为新语法仅在水下使用迭代器。
但是,如果你是指循环旧的
“ c-style”循环:
for(int i=0; i<list.size(); i++) { Object o = list.get(i);}然后,取决于基础数据结构,新的for循环(或迭代器)可能会效率更高。这样做的原因是,对于某些数据结构,
get(i)是
O(n)运算,这使循环成为
O(n 2)运算。传统的链表就是这种数据结构的一个例子。作为基本要求,所有迭代器
next()都应为
O(1)*** 作,从而使循环为
O(n)。
要验证新的
for循环语法在水下使用迭代器,请比较以下两个Java代码段生成的字节码。首先是for循环:
List<Integer> a = new ArrayList<Integer>();for (Integer integer : a){ integer.toString();}// Byte pre ALOAD 1 INVOKEINTERFACE java/util/List.iterator()Ljava/util/Iterator; ASTORE 3 GOTO L2L3 ALOAD 3 INVOKEINTERFACE java/util/Iterator.next()Ljava/lang/Object; CHECKCAST java/lang/Integer ASTORE 2 ALOAD 2 INVOKEVIRTUAL java/lang/Integer.toString()Ljava/lang/String; POPL2 ALOAD 3 INVOKEINTERFACE java/util/Iterator.hasNext()Z IFNE L3其次,迭代器:
List<Integer> a = new ArrayList<Integer>();for (Iterator iterator = a.iterator(); iterator.hasNext();){ Integer integer = (Integer) iterator.next(); integer.toString();}// Bytepre: ALOAD 1 INVOKEINTERFACE java/util/List.iterator()Ljava/util/Iterator; ASTORE 2 GOTO L7L8 ALOAD 2 INVOKEINTERFACE java/util/Iterator.next()Ljava/lang/Object; CHECKCAST java/lang/Integer ASTORE 3 ALOAD 3 INVOKEVIRTUAL java/lang/Integer.toString()Ljava/lang/String; POPL7 ALOAD 2 INVOKEINTERFACE java/util/Iterator.hasNext()Z IFNE L8欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)