This article explains the differences between a for loop and a foreach in depth, and demonstrates it through an instance. 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 ()){...}
For each loop, GetCount () is called 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.
The above is a detailed description of the differences between for loop and foreach. for more information, see other related articles in the first PHP community!