处于该状态的循环评估每个迭代? [英] Is the condition in a for loop evaluated each iteration?

查看:139
本文介绍了处于该状态的循环评估每个迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你做的东西,如:

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

是collection.Count呼吁每个迭代?

is collection.Count called on every iteration?

想,如果Count属性动态获取计数的电话吗?结果变化

Would the result change if the Count property dynamically gets the count on call?

推荐答案

是伯爵将在每一个传球评估。之所以是,它是可能的收集到一个循环的执行过程中进行修改。由于循环结构变量i应该重新present有效的索引到集合中的迭代过程中。如果支票在每个循环却没有这样做,那么这是不是可证明属实。示例情况下

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
}

的CLR JIT将特殊情况下,这类型的循环,在某些情况下,因为阵列的长度不能改变。在这种情况下,边界检查只会发生​​一次。

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.

参考:<一href="http://blogs.msdn.com/brada/archive/2005/04/23/411321.aspx">http://blogs.msdn.com/brada/archive/2005/04/23/411321.aspx

这篇关于处于该状态的循环评估每个迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆