What is the special case with the foreach/for loop that eliminates bounds checking? Also which bounds checking is it?
相关问题
- Is there a limit to how many levels you can nest i
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
See this for details:
http://codebetter.com/blogs/david.hayden/archive/2005/02/27/56104.aspx
Basically, if you have a for loop, and you explicitly refer to IList.Count or Array.Length, the JIT will catch that, and skip the bounds checking. It makes it faster than precomputing the list length.
foreach on a list or array will do the same thing internally, I believe.
A foreach loop uses an enumerator, which is a class or structure that handles the looping. The enumerator has a
Current
property that returns the current item from the collection. That elliminates the use of an index to access the item in the collection, so the extra step to get the item, including bounds checking, is not needed.What? I'm not sure if it is even possible to eliminate bounds checking in c#. If you want unmanaged code, then use:
for example - it doesn't check bounds, and dies terribly. :-)
SealedSun is right. Don't optimize the way you would in C++. JIT is quite smart to do the right thing for you. You can always code the loop in different ways and then inspect the IL code.
Now if optimize the code the way you would in C++ you get the following:
By the way - here is the same with foreach statement:
Don't try to optimize your code without numbers. As you can see JIT will do a lot for your if you don't stand in its way. Use profiler before you optimize. ALWAYS.
The standard
loop is the one that allows the JIT to safely remove array bounds checks (whether the index is within [0..length-1])
The
foreach
loop over arrays is equivalent to that standardfor
loop over arrays.EDIT: As Robert Jeppesen points out:
Thanks! Didn't know that myself.