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?
7 Answers
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).
-
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
-
-
18Hmm, there's a difference on line 5... oh, wait, no that's a spot on my monitor ;) Commented Jul 27, 2010 at 20:12
-
8Are 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
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.
-
2+1 absolutely.
while(true)
is much more clear thanfor(;;)
. What am I waiting for, anyway? Commented Jul 27, 2010 at 20:07 -
1I 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
-
5
-
6I 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
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...
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").
-
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.– supercatCommented Jul 27, 2010 at 20:25
-
@supercat: I agree, but it doesn't justify anything. You should be doing
while (file.getline())
, notfor (;;) 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));"?– supercatCommented Jul 27, 2010 at 23:12
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.
-
3Or you can just look at Fredrik's answer and save yourself the trouble. :)– DarLomCommented Jul 27, 2010 at 20:13
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.
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.");
}
for(;;)
is A) written by former C coders, and B) four characters shorter :)