For Each Loop vs. Iterator: Efficiency in Collection Traversal
Introduction
When traversing a collection in Java, the choice arises between using a for-each loop and an iterator.本文探讨了这两种方法之间的效率差异。
for-east loop 在Java 5中介绍的,for-east loop(也称为loop的增强型)是一个简洁的和易于阅读的概述,并且易于读取概述的概述。它在内部使用迭代器: list
迭代器提供了一个标准化的接口,用于迭代集合。它允许对遍历过程进行自定义控制。
listList很少,请访问量很大, for-each内部使用迭代器机制。a = new ArrayList(); for (Integer integer : a) { integer.toString(); }
,但是,如果使用传统的“ c-style”循环(i):迭代器方法(均可进行循环和显式迭代器)对于某些数据结构而言,效率更高。例如,在链接列表中,get(i)是O(n)操作。 Using an iterator's O(1) next() operation ensures the loop runs in O(n) time, whereas the get(i) loop would run in O(n2
) time.Lista = new ArrayList(); for (Iterator iterator = a.iterator(); iterator.hasNext();) { Integer integer = iterator.next(); integer.toString(); }
To confirm that the for-each loop uses the iterator mechanism, we can compare the generated这两种方法的字节码:
aload 1 InvokeInterface Java/util/list.iterator()ljava/util/iterator; 阿斯托尔3 ...list
aload 1 InvokeInterface Java/util/list.iterator()ljava/util/iterator; ASTORE 2 ...
for (int i = 0; i [&&&&&&&&&&&&&&&&&&&&&&&&&&&& && && && && && &&&&& ussary在摘要中访问唯一的访问集合时,在读取的集合中,是一个for-each for-each iSain isain和each isain isain isain and atar anstain and ataer and ataer andar inator anstar ander inator inator andor andor anstar ander inator。迭代器仅在使用特定数据结构或需要自定义迭代行为时提供优势。为了简单性和可读性,for-EAPE循环通常是首选的选择。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3