The for loop and the foreach loop are all too familiar to Java users, so what do we know about the differences?

The for loop is the basic syntax, which I won’t go into here

Foreach loops, also known as enhanced for loops, are a new feature in JDK5.0. Foreach loops simplify collection traversal, with the disadvantage of losing index information

Foreach loop syntax

for(type element: array){
}
Copy the code

For loop performance comparison with foreach loop

ArrayList<Integer> arrayList = new ArrayList<>();
LinkedList<Integer> linkedList = new LinkedList<>();


for (int i = 0; i < 100000; i++) {
    arrayList.add(i);
    linkedList.add(i);
}

int number;
long start = System.currentTimeMillis();
for (int i = 0; i < arrayList.size(); i++) {
    number = arrayList.get(i);
}
long end = System.currentTimeMillis();
long result = end - start;
System.out.println(ArrayList for loop consumption time: + result);


start = System.currentTimeMillis();
for (int i : arrayList) {
    number = i;
}
end = System.currentTimeMillis();
result = end - start;
System.out.println(ArrayList foreach loop consumption time: + result);


start = System.currentTimeMillis();
for (int i = 0; i < linkedList.size(); i++) {
    number = linkedList.get(i);
}
end = System.currentTimeMillis();
result = end - start;
System.out.println(LinkList for loop consumption time: + result);

start = System.currentTimeMillis();
for (int i : linkedList) {
    number = i;
}
end = System.currentTimeMillis();
result = end - start;
System.out.println(LinkList foreach loop consumption time: + result);
Copy the code

The results

ArrayList forLoop consumption time: 8 ArrayList foreach loop consumption time: 12 LinkListforLinkList foreach loop elapsed time: 3Copy the code

As you can see, the for loop in ArrayList is slightly faster than the foreach loop, and the foreach loop is much faster than the for loop in LinkList

As loops increase, the for loop in an ArrayList is still faster than the foreach loop, while the for loop in a LinkList can get stuck

Conclusion:

  1. Foreach is a new feature in JDK1.5 that enhances the line for loop
  2. Foreach dropped index information
  3. The for loop in ArrayList is faster than the foreach loop
  4. The LinkList foreach loop is faster than the for loop
  5. When iterating through the data of an array structure, it is recommended to use a plain for loop because the for loop uses subscript access
  6. Do not use a regular for loop when iterating through linked list data. Large amounts of data may cause the system to crash