Efficiency between for and foreach

Keywords: Programming

Recently, when I was rolling code, I had a brainstorm and wanted to know the difference between for and foreach, so I searched the data. If you don't say much, post the code first.

Code:

    //for cycle
    public static void main(String[] args) {
        String[] strs = {"3333", "2222", "1111"};
        List<String> list = Arrays.asList(strs);
        list = new ArrayList<>(list);
        for (int i = 0; i < list.size(); i++){
            String str = list.get(i);
            if (i == 2){
                list.remove(str);
                continue;
            }
            System.out.println(str);
        }
    }
    //foreach loop 
    public static void main(String[] args) {
        String[] strs = {"3333", "2222", "1111"};
        List<String> list = Arrays.asList(strs);
        list = new ArrayList<>(list);
        for (String str: list){
            if (str.equals("1111")){
                //Exception throw point
                list.remove(str);
                continue;
            }
            System.out.println(str);
        }
    }

First, analyze the principle. There is nothing to say about the for loop, mainly foreach. The source code of foreach is as follows:

        //next method traversal using iterators
        for (Iterator localIterator = list.iterator(); localIterator.hasNext(); ) {
            //do something...
        }

Because foreach is iterated by using the iterator, an exception is thrown when the last data element is remove d.

for loop operation:

        

foreach cycle operation:

        

The efficiency difference between the two:

In ArrayList, random access is faster than get() in for loop, which is random access. Therefore, in ArrayList, for loop is faster.

In LinkedList, sequential access is faster. In iterator, the next() method is sequential access, so in LinkedList, iterator is faster.

Code:

        

    //Comparison of for cycle and foreach efficiency
    public static void main(String[] args) {
        //LinkedList run
        List<Integer> list = new LinkedList<>();
        //ArrayList running
//        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 100000; i++){
            list.add(i);
        }


        long startTime=System.currentTimeMillis();   //Get start time
        for (int i = 0; i < list.size(); i++){
            //No data output, program running time is too short
            System.out.println(list.get(i));
        }
        long endTime=System.currentTimeMillis(); //Get end time
        long fortime = endTime - startTime;

        startTime=System.currentTimeMillis();   //Get start time
        for (int i : list){
            //No data output, program running time is too short
            System.out.println(i);
        }
        endTime=System.currentTimeMillis(); //Get end time
        System.out.println("for Run time: "+fortime+"ms");
        System.out.println("foreach Run time: "+(endTime - startTime)+"ms");
    }

LinkedList run result:

        

ArrayList run result:

        

As you can see, in the case of ArrayList, the for cycle is slightly faster than foreach, while in the case of LinkedList, the speed of foreach cycle rolls over the for cycle.

Posted by turdferguson on Wed, 30 Oct 2019 07:22:49 -0700