C # provides a new type of loop: foreach, which is closely related to the set interface in the. NET Framework. In the program, we should use foreach for loop first.
Let's take a look at the following code snippet:
Code
1 int [] foo = new int[100];
2
3 // Loop 1:
4 foreach ( int i in foo)
5 Console.WriteLine( i.ToString( ));
6
7 // Loop 2:
8 for ( int index = 0;
9 index < foo.Length;
10 index++ )
11 Console.WriteLine( foo[index].ToString( ));
12
13 // Loop 3:
14 int len = foo.Length;
15 for ( int index = 0;
16 index < len;
17 index++ )
18 Console.WriteLine( foo[index].ToString( ));
19
20
The above Code provides three types of loops. For execution efficiency, the first method adopts the foreach method with the highest efficiency, and the second method adopts the for method with the second efficiency; the third method is to place the Length attribute of the array outside the for loop, which is the most efficient.
C # When the code runs in a hosted environment, every memory used by the program will be checked. This check includes the check for the lower mark of the array. The third method of loop is described above, actually, it is equivalent to the following code.
Code
1 // Loop 3, as generated by compiler:
2 int len = foo.Length;
3 for ( int index = 0;
4 index < len;
5 index++ )
6 {
7 if ( index < foo.Length )
8 Console.WriteLine( foo[index].ToString( ));
9 else
10 throw new IndexOutOfRangeException( );
11 }
Putting the length Out Of The for loop only causes the JIT compiler to do more work and the generated code to be slower. During each iteration of the loop, the program must check whether the array subscript is out of bounds.
We have given priority to the foreach loop from the following aspects.
- Performance, as mentioned above.
- Some people may get used to the array subscript starting from 1, rather than starting from 0. In this case, it will be very troublesome to use the for loop, but foreach has no such troubles.
- For multi-dimensional arrays, multiple layers of for statements need to be written in the for loop mode, while foreach can directly perform one layer.
- In the foreach loop mode, you cannot modify the content of the iteration during each iteration, which can prevent some misoperations.
- If the defined structure changes, for example, from array to arraylist, the call code does not need to be modified for the foreach loop, but for the for loop, the call code needs to be modified, this part of the workload is very cumbersome.
Therefore, foreach is a very useful statement, it uses the correct code that is most efficient to construct the "Upper and Lower Bounds index of array", "multi-dimensional array traversal", and "operand transformation" color number, the most efficient loop structure is generated, which is the best way to traverse the set.