Comparative 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:
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.
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!

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...

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

JDBC...

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

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...

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,...

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...

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...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.