search
HomeJavajavaTutorialComparative analysis of For and For-each applications in Java loops

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){

        }
    }
}

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;
}

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);

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!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Treatment of x² in curve integral: Why can the standard answer be ignored (1/3) x³?Treatment of x² in curve integral: Why can the standard answer be ignored (1/3) x³?Apr 19, 2025 pm 08:06 PM

Questions about a curve integral This article will answer a curve integral question. The questioner had a question about the standard answer to a sample question...

What should I do if the Redis cache of OAuth2Authorization object fails in Spring Boot?What should I do if the Redis cache of OAuth2Authorization object fails in Spring Boot?Apr 19, 2025 pm 08:03 PM

In SpringBoot, use Redis to cache OAuth2Authorization object. In SpringBoot application, use SpringSecurityOAuth2AuthorizationServer...

Why can't the main class be found after copying and pasting the package in IDEA? Is there any solution?Why can't the main class be found after copying and pasting the package in IDEA? Is there any solution?Apr 19, 2025 pm 07:57 PM

Why can't the main class be found after copying and pasting the package in IDEA? Using IntelliJIDEA...

Java multi-interface call: How to ensure that interface A is executed before interface B is executed?Java multi-interface call: How to ensure that interface A is executed before interface B is executed?Apr 19, 2025 pm 07:54 PM

State synchronization between Java multi-interface calls: How to ensure that interface A is called after it is executed? In Java development, you often encounter multiple calls...

In Java programming, how to stop subsequent code execution when student ID is repeated?In Java programming, how to stop subsequent code execution when student ID is repeated?Apr 19, 2025 pm 07:51 PM

How to stop subsequent code execution when ID is repeated in Java programming. When learning Java programming, you often encounter such a requirement: when a certain condition is met,...

Ultimate consistency: What business scenarios are applicable to? How to ensure the consistency of the final data?Ultimate consistency: What business scenarios are applicable to? How to ensure the consistency of the final data?Apr 19, 2025 pm 07:48 PM

In-depth discussion of final consistency: In the distributed system of application scenarios and implementation methods, ensuring data consistency has always been a major challenge for developers. This article...

After the Spring Boot service is running for a period of time, how to troubleshoot?After the Spring Boot service is running for a period of time, how to troubleshoot?Apr 19, 2025 pm 07:45 PM

The troubleshooting idea of ​​SSH connection failure after SpringBoot service has been running for a period of time has recently encountered a problem: a Spring...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.