Is the condition in a for loop evaluated each iteration?

前端 未结 4 508
忘了有多久
忘了有多久 2020-12-17 08:02

When you do stuff like:

for (int i = 0; i < collection.Count; ++i )

is collection.Count called on every iteration?

Would the res

4条回答
  •  北海茫月
    2020-12-17 08:26

    Yes Count will be evaluated on every single pass. The reason why is that it's possible for the collection to be modified during the execution of a loop. Given the loop structure the variable i should represent a valid index into the collection during an iteration. If the check was not done on every loop then this is not provably true. Example case

    for ( int i = 0; i < collection.Count; i++ ) {
      collection.Clear();
    }
    

    The one exception to this rule is looping over an array where the constraint is the Length.

    for ( int i = 0; i < someArray.Length; i++ ) {
      // Code
    }
    

    The CLR JIT will special case this type of loop, in certain circumstances, since the length of an array can't change. In those cases, bounds checking will only occur once.

    Reference: http://blogs.msdn.com/brada/archive/2005/04/23/411321.aspx

提交回复
热议问题