Home  >  Article  >  Backend Development  >  Learn more about the difference between for loop and foreach

Learn more about the difference between for loop and foreach

迷茫
迷茫Original
2017-03-26 10:37:151508browse

The difference between for loop and foreach

foreach relies on IEnumerable.

The first time var a in GetList() is called, GetEnumerator is called to return the first object and assign it to a,

In the future, MoveNext will be called every time var a in GetList() is executed until the end of the loop.

The GetList() method will only be executed once during this period.

foreach   (var a in GetList())
{
    ...
}

=

var a;
IEnumerator  e  =  GetList().GetEnumerator();
while (e.MoveNext)
{
    a = e.Current;
}

for loop is based on the subscript Positioning. list[3] is equivalent to *(list + 3).

for(int i = 0; i < GetCount(); i++)
{
  ....
}

=

int i = 0;

while(i < GetCount())
{
  ...
}

The for loop will call GetCount() to compare the length each time it loops. The foreach does not consider the length and only calls GetList() once.

Conclusion.

The for loop efficiency is higher than foreach when the length is fixed or the length does not need to be calculated.

When the length is uncertain, or there is a performance loss in calculating the length, It is more convenient to use foreach.

And the objects in the collection will be locked during foreach. They cannot be modified during the period.

The above is the detailed content of Learn more about the difference between for loop and foreach. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn