jvb said:
Hey all,
I figure it's Wednesday, why not put a question up for debate. Beyond
personal preference, is there any benefit (performance or otherwise) to
using one loop over the other? For example, I remember in hearing in
class (many years ago...) that VB compiles For...Next loops as
Do...While loops.
Depending on how many years ago it was, the subject in question may
have been VB6 or earlier, about which compiler questions are too much
work (for me) to answer. However, through the wonders of ILDASM, this
question is easy for VB.NET
VB:
Sub Foo()
Dim i As Integer
For i = 1 To 3
Console.WriteLine(i)
Next
End Sub
Sub Bar()
Dim i As Integer
i = 1
Do
Console.WriteLine(i)
i = i + 1
Loop While i <= 3
End Sub
IL:
..method public static void Foo() cil managed
{
// Code size 21 (0x15)
.maxstack 2
.locals init ([0] int32 i)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: call void [mscorlib]System.Console::WriteLine(int32)
IL_0009: nop
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldc.i4.1
IL_000d: add.ovf
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: ldc.i4.3
IL_0011: ble.s IL_0003
IL_0013: nop
IL_0014: ret
} // end of method Module1::Foo
..method public static void Bar() cil managed
{
// Code size 21 (0x15)
.maxstack 2
.locals init ([0] int32 i)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: nop
IL_0004: ldloc.0
IL_0005: call void [mscorlib]System.Console::WriteLine(int32)
IL_000a: nop
IL_000b: ldloc.0
IL_000c: ldc.i4.1
IL_000d: add.ovf
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: ldc.i4.3
IL_0011: ble.s IL_0004
IL_0013: nop
IL_0014: ret
} // end of method Module1::Bar
As you can see, Foo has a nop *before* the WriteLine call, whereas Bar
has a nop *after* the WriteLine call. So... they're different, right?
As someone else said, use the one that makes the most sense. All loops
are really just:
<loop init>
<start>
<loop start action>
....
<loop end action>
<conditional jump to start>