The difference between for loop and foreach is that for loop foreach

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.