For-each vs Iterator. Which will be the better option

后端 未结 8 1305
悲&欢浪女
悲&欢浪女 2020-12-02 09:14

Consider the following scenario.

List list = new ArrayList<>();

Now I added the String values for this li

相关标签:
8条回答
  • 2020-12-02 09:51

    Simple answers: No and no.

    Internally the for-each loop creates an Iterator to iterate through the collection.

    The advantage of using the Iterator explicitly is that you can access the Iterators method.

    0 讨论(0)
  • 2020-12-02 09:54

    Here is simple code snippet to check the performance of For-each vs Iterator vs for for the traversal of ArrayList<String>, performed on Java version 8.

            long MAX = 2000000;
    
            ArrayList<String> list = new ArrayList<>();
    
            for (long i = 0; i < MAX; i++) {
    
                list.add("" + i);
            }
    
            /**
             * Checking with for each iteration.
             */
            long A = System.currentTimeMillis();
    
            for (String data : list) {
                // System.out.println(data);
            }
    
            long B = System.currentTimeMillis();
            System.out.println(B - A + "ms");
    
            /**
             * Checking with Iterator method
             */
    
            Iterator<String> iterator = list.iterator();
            while (iterator.hasNext()) {
                iterator.next();
                // System.out.println(iterator.next());
            }
    
            long C = System.currentTimeMillis();
            System.out.println(C - B + "ms");
    
            /**
             * Checking with normal iteration.
             */
            for (int i = 0; i < MAX; i++) {
                list.get((int) (i % (MAX - i)));
                // System.out.println(list.get(i));
            }
    
            long D = System.currentTimeMillis();
            System.out.println(D - C + "ms");
    

    Average Output values:

    19ms
    9ms
    27ms
    

    Result Analysis: Iterator (9ms) < For-each (19ms) < For (27ms)

    Here Iterator has the best performance and For has the least performance. However For-each performance lies somewhere in between.

    0 讨论(0)
提交回复
热议问题