Effective C # principle 11: Select a foreach Loop

Source: Internet
Author: User
Tags foreach arrays tostring

C # 's foreach statement is a change from a do,while, or a For loop statement, which is relatively better, and it can produce the best iteration code for any of your collections. Its definition is lazy. NET Framework, and the compiler generates the best code for the actual collection. When you iterate over the collection, you can use foreach to replace the other loop structure. Check the following three loops:

int [] foo = new int[100];
// Loop 1:
foreach ( int i in foo)
 Console.WriteLine( i.ToString( ));
// Loop 2:
for ( int index = 0; index < foo.Length; index++ )
 Console.WriteLine( foo[index].ToString( ));
// Loop 3:
int len = foo.Length;
for ( int index = 0; index < len; index++ )
 Console.WriteLine( foo[index].ToString( ));

For the current C # compiler (version 1.1 or higher), loop 1 is the best. At least it's less input, which will increase your personal development efficiency. (The 1.0 C # compiler is a lot slower for loop 1, so it's best for that version of Cycle 2.) 3, most C or C + + programmers will think it's the most effective, but it's the worst. Because the value of the variable length is removed outside the loop, the JIT compiler is prevented from moving boundary detection out of the loop.

C # code is run in secure managed code. Every piece of memory in the environment, including the index of the data, is monitored. In a little bit, the Loop 3 code actually looks something like this:

// Loop 3, as generated by compiler:
int len = foo.Length;
for ( int index = 0; index < len; index++ )
{
 if ( index < foo.Length )
  Console.WriteLine( foo[index].ToString( ));
 else
   throw new IndexOutOfRangeException( );
}

The JIT compiler for C # is not like you, it's trying to help you do that. You wanted to put the length attribute out of the loop, but it made the compilation do more things, and thus slowed down. One of the things the CLR wants to guarantee is that you can't write code that accesses a variable to its own memory. When accessing each actual collection, the runtime ensures that the bounds of each collection (not the Len variable) are detected. You divide a boundary detection into two.

You still have to do an index test for each iteration of the loop, and it's two times. Loop 1 and loop 2 are faster because the JIT compiler of C # can verify the bounds of the array to ensure security. When any loop variable is not the length of the data, boundary detection occurs in each iteration. Here are a few times when you talk about the JIT compiler, which is the compiler that compiles the IL code at the cost of the code, not the compiler that compiles the C # code or other code into IL code. In fact, we can use the unsafe option to force the JIT does not do such a test, so that the speed of the operation increased. )

The original C # compiler produces slow code for foreach and arrays because boxing is involved. Boxing will be discussed in principle 17. Arrays are security types, and now foreach can generate IL code that is different from other collections in an array. For this version of the array, it no longer uses the IEnumerator interface, that is, the interface needs to be boxed and disassembled.

IEnumerator it = foo.GetEnumerator( );
while( it.MoveNext( ))
{
 int i = (int) it.Current; // box and unbox here.
 Console.WriteLine( i.ToString( ) );
}

Instead, the foreach statement generates such a structure for an array:

for ( int index = 0; index < foo.Length; index++ )
 Console.WriteLine( foo[index].ToString( ));

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.