The difference between for loop and foreach is that for loop foreach
Differences between for loop and foreach
Foreach depends on IEnumerable.
The first time var a in GetList () is called, GetEnumerator returns the first object and assigns it to,
Call MoveNext every time var a in GetList () is executed. The loop ends.
The GetList () method is executed only once.
Foreach (var a in GetList ()){...} = var a; IEnumerator e = GetList (). getEnumerator (); while (e. moveNext) {a = e. current ;}
For Loop positioning by subscript. list [3] is equivalent to * (list + 3 ).
For (int I = 0; I <GetCount (); I ++ ){....} = int I = 0; while (I <GetCount ()){...}
Or each loop calls GetCount () to compare the length. While foreach does not consider the length, only GetList () is called once ().
Conclusion.
When fixed length or length does not need to be calculated, the for loop efficiency is higher than that of foreach.
When the length is not determined, or the computing length has performance loss, it is more convenient to use foreach.
In addition, foreach locks the objects in the set. The objects cannot be modified during this period.