Home > Java > javaTutorial > body text

Comparative analysis of For and For-each applications in Java loops

王林
Release: 2023-05-25 14:56:08
forward
1183 people have browsed it

for-each implementation method

For-each is not a new syntax, but syntax sugar for Java. At compile time, the compiler converts this code into an iterator implementation and compiles it into bytecode. We can decompile the following compiled code by executing the command javap-verbose-Testforeach:

public class TestForeach {
    List<Integer> integers;
    public void testForeach(){
        for(Integer i : integers){

        }
    }
}
Copy after login

The detailed bytecode obtained is as follows:

public void testForeach();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=1, locals=3, args_size=1
         0: aload_0
         1: getfield      #2                  // Field integers:Ljava/util/List;
         4: invokeinterface #3,  1            // InterfaceMethod java/util/List.iterator:()Ljava/util/Iterator;
         9: astore_1
        10: aload_1
        11: invokeinterface #4,  1            // InterfaceMethod java/util/Iterator.hasNext:()Z
        16: ifeq          32
        19: aload_1
        20: invokeinterface #5,  1            // InterfaceMethod java/util/Iterator.next:()Ljava/lang/Object;
        25: checkcast     #6                  // class java/lang/Integer
        28: astore_2
        29: goto          10
        32: return
      LineNumberTable:
        line 11: 0
        line 13: 29
        line 14: 32
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
           29       0     2     i   Ljava/lang/Integer;
            0      33     0  this   Ltest/TestForeach;
}
Copy after login

General of this bytecode The meaning is to use the getfileld command to get the integers variable and call List.iterator to get the iterator instance and call iterator.hasNext. If true is returned, call the iterator.next method.

Please see, this is the implementation logic of iterator traversing the collection.

Benchmarking

Now let us test using for loop method and for-each method.

public class ForLoopTest {

    public static void main(String[] args) {
        List<Integer> arrayList = new ArrayList<>();
        for (int i = 0; i < 10000000; i++) {
            arrayList.add(i);
        }

        long arrayListStartTime = System.currentTimeMillis();
        for (int i = 0; i < arrayList.size(); i++) {
            arrayList.get(i);
        }

        long arrayListCost =System.currentTimeMillis()-arrayListStartTime;
        System.out.println("ArrayList for loop traversal cost: "+ arrayListCost);

        long arrayListForeachStartTime = System.currentTimeMillis();
        for (Integer integer : arrayList) {

        }

        long arrayListForeachCost =System.currentTimeMillis()-arrayListForeachStartTime;
        System.out.println("ArrayList foreach traversal cost: "+ arrayListForeachCost);
Copy after login

Here are the test results:

Comparative analysis of For and For-each applications in Java loops

As you can see, the results are obvious. Using the For loop method is more efficient on ArrayList than the For each method.

Can we say that for loop is better than for-each?

the answer is negative. In the next benchmark, we change the ArrayList to a LinkedList.
Again, here are the test results.

Comparative analysis of For and For-each applications in Java loops

Cause Analysis

Some beginners may wonder why ArrayList uses the for loop method to traverse faster, while LinkedList is slower and very slow ?

This is determined by the ArrayList and LinkedList data structures.
The bottom layer of ArrayList uses arrays to store elements. Arrays are contiguous memory spaces. Data can be obtained through indexes. The time complexity is O(1), so it's fast.

The bottom layer of LinkedList is a doubly linked list. Use a for loop to implement traversal, starting from the head node of the linked list each time. The time complexity is O(n*n).

Conclusion

  • When using ArrayList, the for loop method is faster because for-each is implemented by iterators and needs to perform concurrent modification verification.

  • When using LinkedList, for-each is much faster than for loop because LinkedList is implemented by using a doubly linked list. Every addressing needs to start from the head node. When iterating over a LinkedList, avoid using for loops.

  • Using the iterator pattern, for-each does not need to care about the specific implementation of the collection. If a collection needs to be replaced, it can be easily done without modifying the code.

The above is the detailed content of Comparative analysis of For and For-each applications in Java loops. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template