Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 哪种方法是迭代特定集合元素的最佳方法?_Java_Loops_Collections - Fatal编程技术网

Java 哪种方法是迭代特定集合元素的最佳方法?

Java 哪种方法是迭代特定集合元素的最佳方法?,java,loops,collections,Java,Loops,Collections,在浏览特定集合的元素时,我总是对每个循环使用 为了检查每个循环过程消耗的时间,我这样编码 public class LoopingDemo { static ArrayList<String> arrayList = new ArrayList<String>(); static double start; static double end; public static void iterator() { simpleF

在浏览特定集合的元素时,我总是对每个循环使用

为了检查每个循环过程消耗的时间,我这样编码

public class LoopingDemo {
    static ArrayList<String> arrayList = new ArrayList<String>();
    static double start;
    static double end;

    public static void iterator() {
        simpleForLoop();
        System.out.println();
        forEachLoop();
        System.out.println();
        useWhileLoop(arrayList);
        System.out.println();
        useForLoop(arrayList);
        System.out.println();
        enumerator();
    }
    public static void simpleForLoop(){
        start = System.nanoTime();
        for(int i=0;i<arrayList.size();i++){
            String str = arrayList.get(i);
            System.out.println(": "+str);
        }
        end = System.nanoTime();
        System.out.println("Taken taken in simpleForLoop process: "
            + (end - start));
    }

    public static void forEachLoop() {
        start = System.nanoTime();
        for (String str : arrayList) {
        System.out.println(str);
    }
        end = System.nanoTime();
        System.out.println("Taken taken in forEachLoop process: "
            + (end - start));
    }

    public static void enumerator() {
        start = System.nanoTime();

        // get the Enumeration object
        Enumeration<String> en = Collections.enumeration(arrayList);

        // enumerate through the ArrayList elements
        System.out.println("Enumerating through Java ArrayList");

        while (en.hasMoreElements()) {
            System.out.println(en.nextElement());
            /*
             * String name = (String) en.nextElement();
             * System.out.println(name);
             */
        } 
        end = System.nanoTime();
        System.out.println("Taken taken in enumeration process: "
            + (end - start));
    }

    private static void useWhileLoop(Collection<String> myList) {
        start = System.nanoTime();
        Iterator<String> itr = myList.iterator();
        while (itr.hasNext()) {
            String str = itr.next(); // Returns the next element in the
                                    // iteration.
            System.out.println(str);
            // System.out.println(itr.next()); // in one line
        }
        end = System.nanoTime();
        System.out.println("Taken taken in useWhileLoop process: "
            + (end - start));
    }

    /**
     * Note that this for-loop does not use an integer index.
     */
    private static void useForLoop(Collection<String> myList) {
        start = System.nanoTime();
        for (Iterator<String> itr = myList.iterator(); itr.hasNext();) {
            System.out.println(itr.next());
        }
        end = System.nanoTime();
        System.out.println("Taken taken in useForLoopWithIterator process: "
            + (end - start));
    }

    public static void addElements() {

        // Add elements to the array list.
        arrayList.add("C");
        arrayList.add("A");
        arrayList.add("E");
        arrayList.add("B");
        arrayList.add("D");
        arrayList.add("F");
        arrayList.add(1, "A2");

    }

    public static void main(String[] args) {
        addElements();
        iterator();

    }

}

那么为什么人们更喜欢通过for each循环来实现呢?是否有任何基于绩效的原因

我使用它是为了方便。你不需要用“类型E:集合”来考虑边界和条件。只要代码足够快,我就会追求简单性和可维护性。只有性能成为问题时,我才会考虑优化。即使这样,也可能有部分工作流在优化时会产生更大的性能收益。

< P>有效的java覆盖了这一点。基本上,前文简洁明了。对于任何阅读和理解代码的人来说。人们总是说永远不要过早地优化。只有在你绝对确定需要优化时才考虑优化。因此,如果你发现foreach非常常见,那是因为它更容易理解、维护和优化在那一刻被确定为不需要。

IIRC,for each循环只是一个语法糖,当遍历集合时,将使用迭代器编译为for循环。在运行时,应该没有性能差异

您所看到的差异是编写糟糕的基准测试逻辑的典型结果。如果您将“for loop with iterator”作为第一个调用的方法,您会发现它运行缓慢

更不用说每次测试的持续时间太短而不重要,在我添加了一些热身后(先运行所有测试5次,然后查看第6次结果),结果变得正常:

Taken taken in useForLoopWithIterator process: 105110.0
Taken taken in simpleForLoop process: 122181.0
Taken taken in useWhileLoop process: 104774.0
Taken taken in enumeration process: 123520.0
Taken taken in forEachLoop process: 106782.0

forEachloop、useForLoopWithIterator和useWhileLoop的结果几乎相同(它们应该是相同的)。通过集合进行迭代时,基于索引的访问几乎是最不受欢迎的。虽然这里的差异并不显著,但如果使用非基于数组的集合,例如LinkedList,您将看到更大的差异。

”代码越少越好”,而且速度也够快“。这不是一个设计良好的基准,我不相信它的结果能够代表现实世界的性能行为。如果您想要可靠的结果,请使用JMH或Caliper之类的基准测试框架。虽然迭代器和for-each循环确实比索引循环有一些开销,但开销比基准测试中显示的要小。
Taken taken in useForLoopWithIterator process: 105110.0
Taken taken in simpleForLoop process: 122181.0
Taken taken in useWhileLoop process: 104774.0
Taken taken in enumeration process: 123520.0
Taken taken in forEachLoop process: 106782.0