并同时循环在c# [英] for and while loop in c#

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

问题描述

 为(i = 0; I< = 10;我++)
{
    ..
    ..
}I = 0;
而(ⅰ&下; = 10)
{
    ..
    ..
    我++;
}

在为和while循环,哪一个更好,性能明智?


解决方案

(更新)
事实上 - 有一种情况,其中构造更有效;循环阵列上。编译器/ JIT的优化已经为这种情况的只要您使用 arr.Length 在条件的:

 的for(int i = 0; I< arr.Length;我++){
    Console.WriteLine(ARR [I]); //跳过范围检查
}

在这个非常特殊的情况下,跳过边界检查,因为它已经知道它永远不会出界。有趣的是,如果你葫芦 arr.Length 来尝试手动优化它,你prevent这种情况的发生:

  INT LEN = arr.Length;
的for(int i = 0; I< LEN,我++){
    Console.WriteLine(ARR [I]); //执行范围检查
}

不过,与其他容器(列表< T> 等),吊装作为手动微优化还算合理

(最终更新)


既不; for循环被评为引擎盖下反正while循环。

例如ECMA 334(明确赋值)的12.3.3.9决定了一个for循环:

 的(换初始化;对于条件;对于迭代器)嵌入语句

实质上等同(从明确赋值角度(不太一样说编译器必须生成此IL))为:

  {
    对于初始值设定;
    而(为条件){
        嵌入语句;
        LLOOP:
        对于迭代器;
    }
}


  

与继续针对报表
  for语句被翻译成
  goto语句瞄准标签
  LLOOP。如果省略了条件
  从for语句,然后
  明确赋值的评价
  所得款项用作如果条件是
  在上述与真正的替代
  扩展。


现在,这并不意味着,编译器必须做同样的事情,但在现实中却pretty钱?...

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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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