在C#中(;;),虽然(真)之间的区别? [英] Difference between for(;;) and while (true) in C#?

查看:122
本文介绍了在C#中(;;),虽然(真)之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在语法上我看到他们无限循环,直到break语句达到了,但他们编译为同样的事情?是的稍快一些,因为它不具备一个条件检查?除了代码的可读性,是甚至有区别

Syntactically I see that they loop indefinitely until a break statement is reached, but are they compiled to the same thing? Is the for slightly faster because it doesn't have a condition to check? Aside from code readability, is there even a difference?

推荐答案

鉴于这种输入:

private static void ForLoop()
{
    int n = 0;
    for (; ; )
    {
        Console.WriteLine(n++);
    }
}

private static void WhileLoop()
{
    int n = 0;
    while (true)
    {
        Console.WriteLine(n++);
    }
}



...你得到这样的输出:

...you get this output:

.method private hidebysig static void  ForLoop() cil managed
{
  // Code size       14 (0xe)
  .maxstack  3
  .locals init ([0] int32 n)
  IL_0000:  ldc.i4.0
  IL_0001:  stloc.0
  IL_0002:  ldloc.0
  IL_0003:  dup
  IL_0004:  ldc.i4.1
  IL_0005:  add
  IL_0006:  stloc.0
  IL_0007:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_000c:  br.s       IL_0002
} // end of method Program::ForLoop


.method private hidebysig static void  WhileLoop() cil managed
{
  // Code size       14 (0xe)
  .maxstack  3
  .locals init ([0] int32 n)
  IL_0000:  ldc.i4.0
  IL_0001:  stloc.0
  IL_0002:  ldloc.0
  IL_0003:  dup
  IL_0004:  ldc.i4.1
  IL_0005:  add
  IL_0006:  stloc.0
  IL_0007:  call       void [mscorlib]System.Console::WriteLine(int32)
  IL_000c:  br.s       IL_0002
} // end of method Program::WhileLoop

非常相似,我会说(相同的,甚至是)。

Remarkably similar, I would say (identical, even).

这篇关于在C#中(;;),虽然(真)之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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