17

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?

3
  • See stackoverflow.com/questions/2288856/… Commented Jul 27, 2010 at 20:17
  • This is a good question. I find it interesting to see that the compiler optimizes the code down to a do while loop in the example code I tried this with.
    – Wil P
    Commented Jul 27, 2010 at 20:23
  • 1
    for(;;) is A) written by former C coders, and B) four characters shorter :)
    – hobbs
    Commented Jul 29, 2010 at 4:26

7 Answers 7

36

Given this input:

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).

9
  • Unless I'm missing something, they are identical, outside of the comments and identifier names.
    – T.E.D.
    Commented Jul 27, 2010 at 20:11
  • @T.E.D. yes, they are identical. Commented Jul 27, 2010 at 20:11
  • 18
    Hmm, there's a difference on line 5... oh, wait, no that's a spot on my monitor ;)
    – Mike Caron
    Commented Jul 27, 2010 at 20:12
  • 8
    Are we really debating the relative speed of infinite loops? Commented Jul 27, 2010 at 20:27
  • 2
    @Steven: I certainly hope not. We are satisfying our curiosity. At least I am. Commented Jul 27, 2010 at 20:30
21

In modern compilers, absolutely nothing.

Historically, however, for(;;) was implemented as a single jump, while while(true) also had a check for true.

I prefer while(true), since it makes it more clear what I am doing.

11
  • 2
    +1 absolutely. while(true) is much more clear than for(;;). What am I waiting for, anyway? Commented Jul 27, 2010 at 20:07
  • 1
    I heartily agree that you should pick the one you think is clearer, although I might disagree on which one that is...
    – T.E.D.
    Commented Jul 27, 2010 at 20:08
  • 2
    why not loop: ... goto loop ? Commented Jul 27, 2010 at 20:10
  • 5
    OMG! NOT goto! IF WE USE THAT, THE WORLD WILL END!
    – Mike Caron
    Commented Jul 27, 2010 at 20:11
  • 6
    I don't think the world would end if we used goto, but it might abruptly jump to a new location in the universe. Commented Jul 27, 2010 at 20:38
2

I haven't examined the output code, but there should be no difference whatsoever. Any decent compiler will do simple enough loop optimization to see that the condition is a constant expression, and thus doesn't need checking every iteration.

If one is faster than the other, the C# compiler writers need something 'splained to them...

1

If I might, I'd suggest that you look at a somewhat different question. If you're using either of these often enough to care, you're probably structuring your code poorly. While there are things like embedded systems that really do run forever, loops in most normal code do not. Writing a loop that claims to run forever usually means you've hidden the exit condition for the loop somewhere inside, with some other control flow (e.g., if (whatever) break;) as the real exit from the loop.

That can and usually should be avoided. While there are situations where break statements make sense, they should generally be to handle unusual situations, not for writing a loop that says one thing but does another (i.e., says "run forever", but really does "run until condition is met").

12
  • Me neither. When I was first learning to program in PL/I (I don't know if it even had a 'break' statement) the pattern was "read line of file; while it's not the end-marker, do the loop, which ends with reading the next line". That seems a violation of "don't repeat yourself". I would suggest that reading the line once, at the start of the loop, and exiting if it's an end-marker, is a better style.
    – supercat
    Commented Jul 27, 2010 at 20:25
  • @supercat: I agree, but it doesn't justify anything. You should be doing while (file.getline()), not for (;;) if (!file.getline()) break; Commented Jul 27, 2010 at 20:31
  • @supercat: Yes, it's often cleanest to put the test into the middle of the loop and break out of it when it fails. Commented Jul 27, 2010 at 20:37
  • @Jerry: That's a plausible example, but hardly the only way things work. The sentinel could instead be a specific value, such as a "0". Commented Jul 27, 2010 at 20:38
  • 1
    @Jerry Coffin: That while() loop condition exceeds my threshold for how many side-effects an expression can have before it's considered ridiculous. Why bother with a loop body at all? Why not "while ((((x=next_value()) != sentinel) && (process(x),1));"?
    – supercat
    Commented Jul 27, 2010 at 23:12
0

They compile to the same thing. You can write a test app that implements both methods and then use ILDASM to confirm they IL is identical.

1
  • 3
    Or you can just look at Fredrik's answer and save yourself the trouble. :)
    – DarLom
    Commented Jul 27, 2010 at 20:13
0

As mentioned by others, with any modern compiler, it should make absolutely no difference.

I did a brief test on my computer, timing a couple of operations using one or the other, and they always took pretty much the same time. Of course, because of other processes running, these tests aren't 100% accurate, but if there is a difference in speed (there shouldn't be) then it is a microscopic one.

0

A debug assembly complies down to while(true). Use reflector and you can see the results.

    static void Main(string[] args)
    {
        ExecuteWhile();

        ExecuteFor();
    }

    private static void ExecuteFor()
    {
        for (; ; )
        {
            Console.WriteLine("for");
            string val = Console.ReadLine();
            if (string.IsNullOrEmpty(val))
            {
                Console.WriteLine("Exit for.");
                break;
            }
        }
    }

    private static void ExecuteWhile()
    {
        while (true)
        {
            Console.WriteLine("while");
            string val = Console.ReadLine();
            if (string.IsNullOrEmpty(val))
            {
                Console.WriteLine("Exit while.");
                break;
            }
        }
    }

Inspecting the ExecuteFor method in Reflector.

private static void ExecuteFor()
{
    while (true)
    {
        Console.WriteLine("for");
        if (string.IsNullOrEmpty(Console.ReadLine()))
        {
            Console.WriteLine("Exit for.");
            return;
        }
    }
}

An optimized version of the same code produces different results for ExecuteFor

private static void ExecuteFor()
{
    do
    {
        Console.WriteLine("for");
    }
    while (!string.IsNullOrEmpty(Console.ReadLine()));
    Console.WriteLine("Exit for.");
}

For verbosity here is the optimized ExecuteWhile...

private static void ExecuteWhile()
{
    do
    {
        Console.WriteLine("while");
    }
    while (!string.IsNullOrEmpty(Console.ReadLine()));
    Console.WriteLine("Exit while.");
}
2
  • Does it really compile down to while(true), or does Reflector decompile it that way? :p
    – Mark H
    Commented Jul 27, 2010 at 20:18
  • If you look at the IL created from the same assemblies it reads that way.
    – Wil P
    Commented Jul 27, 2010 at 20:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.