C#中的for和while循环 [英] for and while loop in c#

查看:26
本文介绍了C#中的for和while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for (i=0 ; i<=10; i++){....}我=0;而(i<=10){....我++;}

在 for 和 while 循环中,哪个更好,性能方面?

解决方案

(update)实际上 - 在一种情况下 for 构造更有效;在数组上循环.编译器/JIT 已针对此场景进行了优化只要您在条件中使用 arr.Length :

for(int i = 0 ; i 

在这个非常特殊的情况下,它跳过边界检查,因为它已经知道它永远不会越界.有趣的是,如果您提升"arr.Length 以尝试手动优化它,您可以防止这种情况发生:

int len = arr.Length;for(int i = 0 ; i < len ; i++) {Console.WriteLine(arr[i]);//执行边界检查}

然而,对于其他容器(List 等),提升作为手动微优化是相当合理的.

(结束更新)

<小时>

都不是;无论如何,for 循环在后台被评估为 while 循环.

例如 ECMA 334 的 12.3.3.9(明确分配)规定了 for 循环:

for ( for-initializer ; for-condition ; for-iterator ) 嵌入语句

本质上是等价的(从明确赋值的角度来看(与说编译器必须生成这个IL"不完全相同))为:

<代码>{初始化器;而(条件){嵌入语句;循环:for-迭代器;}}

<块引用>

带有针对目标的 continue 语句被翻译成的 for 语句针对标签的 goto 语句循环.如果省略 for 条件从 for 语句,然后确定分配的评估就像 for-condition 一样进行在上面替换为 true扩展.

现在,这并不意味着编译器必须做完全相同的事情,但实际上它几乎可以......

for (i=0 ; i<=10; i++)
{
    ..
    ..
}

i=0;
while(i<=10)
{
    ..
    ..
    i++;
}

In for and while loop, which one is better, performance wise?

解决方案

(update) Actually - there is one scenario where the for construct is more efficient; looping on an array. The compiler/JIT has optimisations for this scenario as long as you use arr.Length in the condition:

for(int i = 0 ; i < arr.Length ; i++) {
    Console.WriteLine(arr[i]); // skips bounds check
}

In this very specific case, it skips the bounds checking, as it already knows that it will never be out of bounds. Interestingly, if you "hoist" arr.Length to try to optimize it manually, you prevent this from happening:

int len = arr.Length;
for(int i = 0 ; i < len ; i++) {
    Console.WriteLine(arr[i]); // performs bounds check
}

However, with other containers (List<T> etc), hoisting is fairly reasonable as a manual micro-optimisation.

(end update)


Neither; a for loop is evaluated as a while loop under the hood anyway.

For example 12.3.3.9 of ECMA 334 (definite assignment) dictates that a for loop:

for ( for-initializer ; for-condition ; for-iterator ) embedded-statement

is essentially equivalent (from a Definite assignment perspective (not quite the same as saying "the compiler must generate this IL")) as:

{
    for-initializer ;
    while ( for-condition ) {
        embedded-statement ;
        LLoop:
        for-iterator ;
    }
}

with continue statements that target the for statement being translated to goto statements targeting the label LLoop. If the for-condition is omitted from the for statement, then evaluation of definite assignment proceeds as if for-condition were replaced with true in the above expansion.

Now, this doesn't mean that the compiler has to do exactly the same thing, but in reality it pretty much does...

这篇关于C#中的for和while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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