如果您查看 MSIL,您会发现不同之处在于变量声明:
.method public hidebysig static
void task1 () cil managed
{
.locals init (
[0] int32 i
)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: br.s IL_000e
.loop
{
IL_0004: ldloc.0
IL_0005: call void [mscorlib]System.Console::WriteLine(int32)
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: add
IL_000d: stloc.0
IL_000e: ldloc.0
IL_000f: ldc.i4.s 10
IL_0011: blt.s IL_0004
}
IL_0013: ldc.i4.0
IL_0014: stloc.0
IL_0015: br.s IL_0021
.loop
{
IL_0017: ldloc.0
IL_0018: call void [mscorlib]System.Console::WriteLine(int32)
IL_001d: ldloc.0
IL_001e: ldc.i4.1
IL_001f: add
IL_0020: stloc.0
IL_0021: ldloc.0
IL_0022: ldc.i4.s 100
IL_0024: blt.s IL_0017
}
IL_0026: ret
}
第二种情况:
.method public hidebysig static
void task2 () cil managed
{
.locals init (
[0] int32 i,
[1] int32 i
)
IL_0000: ldc.i4.0
IL_0001: stloc.0
IL_0002: br.s IL_000e
.loop
{
IL_0004: ldloc.0
IL_0005: call void [mscorlib]System.Console::WriteLine(int32)
IL_000a: ldloc.0
IL_000b: ldc.i4.1
IL_000c: add
IL_000d: stloc.0
IL_000e: ldloc.0
IL_000f: ldc.i4.s 10
IL_0011: blt.s IL_0004
}
IL_0013: ldc.i4.0
IL_0014: stloc.1
IL_0015: br.s IL_0021
.loop
{
IL_0017: ldloc.1
IL_0018: call void [mscorlib]System.Console::WriteLine(int32)
IL_001d: ldloc.1
IL_001e: ldc.i4.1
IL_001f: add
IL_0020: stloc.1
IL_0021: ldloc.1
IL_0022: ldc.i4.s 100
IL_0024: blt.s IL_0017
}
IL_0026: ret
}
不同之处在于一个本地声明。并将其加载到内存中。在第一种情况下,它两次加载变量。