简体   繁体   English

在C#中,每次都会评估循环声明吗?

[英]Within C# is a loop declaration evaluated each time?

This is a really nit-picky question, but curiosity got the better of me. 这是一个非常挑剔的问题,但好奇心使我变得更好。

Does a for loop re-evaluate the RHS condition each time the loop executes? 每次循环执行时,for循环是否会重新评估RHS条件? See below. 见下文。

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

Is it good practice throughout your code base to do the following? 在您的代码库中执行以下操作是否是一种好习惯?

for(int i = 0, n = collections.Count; i < n; i++)
{
}

Or does the compiler do these kind of optimisations / they're negligible (even with a huge code base)? 还是编译器进行了此类优化/它们可以忽略不计(即使具有庞大的代码库)?

The condition will be reevaluated before every iteration (unless the compiler detects that the condition is constant), and it is acceptable to write code that depends on this (such as calling a function whose return value will be different each time). 在每次迭代之前重新评估条件(除非编译器检测到条件是恒定的),并且可以编写依赖于此的代码(例如调用每次返回值都不同的函数)是可以接受的。 Thus, if you have a condition that is expensive to evaluate and you are sure it will remain constant, it is indeed a good idea to evaluate it once, before the loop. 因此,如果您要评估的条件很昂贵,并且确定它会保持不变,那么在循环之前对它进行一次评估确实是个好主意。 However, for most standard collection types, Count is such a fast operation that the negligible performance gain won't be worth the reduced readability. 但是,对于大多数标准集合类型而言, Count运算速度如此之快,以至于微不足道的性能提升将不值得以降低的可读性为代价。

if the right of the condition is constant (so it doesn't change in the loops internals) I believe the optimizer moves the collections.Count outside the top of the loop. 如果条件的右边是常数(因此在循环内部不会改变),我相信优化程序会将collection.Count移到循环顶部之外。 If the collection is modified in the loop it would evaluated every-time. 如果在循环中修改了集合,则它将每次进行评估。

if you used a foreach you will notice that you can't change the enumerator inside the loop because foreach uses this optimization to be a quicker loop.... 如果您使用了foreach,则会注意到您无法在循环内更改枚举数,因为foreach使用此优化方法可以使循环更快。

You could always write a small demo app with a couple of loops one that modifies within the loop and one that doesn't and then run ildasm on it and see what code gets generated. 您总是可以编写一个带有两个循环的小型演示应用程序,一个循环在循环内进行修改,另一个循环不进行修改,然后在其上运行ildasm并查看生成的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM