Learn more about the difference between for loop and foreach

迷茫
Release: 2023-03-06 22:34:01
Original
1542 people have browsed it

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;
}
Copy after login

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())
{
  ...
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!