C# for 循环反汇编中的无用变量与捕获委托?

the*_*rge 5 c# closures for-loop disassembly

我试图看一下这个老问题中发布的代码的反汇编,我发现了一些奇怪的东西。

为了清楚起见,这是源代码:

class ThreadTest
{
    static void Main(string[] args)
    {
        for (int i = 0; i < 10; i++)
            new Thread(() => Console.WriteLine(i)).Start();
    }
}
Run Code Online (Sandbox Code Playgroud)

(当然这个程序的行为是出乎意料的,这不是这里的问题。)

这是我在反汇编中看到的:

internal class ThreadTest
{
    private static void Main(string[] args)
    {
        int i;
        int j;
        for (i = 0; i < 10; i = j + 1)
        {
            new Thread(delegate
            {
                Console.WriteLine(i);
            }).Start();
            j = i;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在那里做什么j?这是字节码:

.method private hidebysig static 
    void Main (
        string[] args
    ) cil managed 
{
    // Method begins at RVA 0x2050
    // Code size 64 (0x40)
    .maxstack 2
    .entrypoint
    .locals init (
        [0] class ConsoleApplication2.ThreadTest/'<>c__DisplayClass0_0' 'CS$<>8__locals0',
        [1] int32
    )

    IL_0000: newobj instance void ConsoleApplication2.ThreadTest/'<>c__DisplayClass0_0'::.ctor()
    IL_0005: stloc.0
    IL_0006: ldloc.0
    IL_0007: ldc.i4.0
    IL_0008: stfld int32 ConsoleApplication2.ThreadTest/'<>c__DisplayClass0_0'::i
    IL_000d: br.s IL_0035
    // loop start (head: IL_0035)
        IL_000f: ldloc.0
        IL_0010: ldftn instance void ConsoleApplication2.ThreadTest/'<>c__DisplayClass0_0'::'<Main>b__0'()
        IL_0016: newobj instance void [mscorlib]System.Threading.ThreadStart::.ctor(object, native int)
        IL_001b: newobj instance void [mscorlib]System.Threading.Thread::.ctor(class [mscorlib]System.Threading.ThreadStart)
        IL_0020: call instance void [mscorlib]System.Threading.Thread::Start()
        IL_0025: ldloc.0
        IL_0026: ldfld int32 ConsoleApplication2.ThreadTest/'<>c__DisplayClass0_0'::i
        IL_002b: ldc.i4.1
        IL_002c: add
        IL_002d: stloc.1
        IL_002e: ldloc.0
        IL_002f: ldloc.1
        IL_0030: stfld int32 ConsoleApplication2.ThreadTest/'<>c__DisplayClass0_0'::i

        IL_0035: ldloc.0
        IL_0036: ldfld int32 ConsoleApplication2.ThreadTest/'<>c__DisplayClass0_0'::i
        IL_003b: ldc.i4.s 10
        IL_003d: blt.s IL_000f
    // end loop

    IL_003f: ret
} // end of method ThreadTest::Main
Run Code Online (Sandbox Code Playgroud)

但这是最奇怪的事情。如果我像这样更改原始代码,替换i++i = i + 1

class ThreadTest
{
    static void Main(string[] args)
    {
        for (int i = 0; i < 10; i = i + 1)
            new Thread(() => Console.WriteLine(i)).Start();
    }
}
Run Code Online (Sandbox Code Playgroud)

我明白了:

internal class ThreadTest
{
    private static void Main(string[] args)
    {
        int i;
        for (i = 0; i < 10; i++)
        {
            new Thread(delegate
            {
                Console.WriteLine(i);
            }).Start();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这正是我所期望的。

这是字节码:

.method private hidebysig static 
    void Main (
        string[] args
    ) cil managed 
{
    // Method begins at RVA 0x2050
    // Code size 62 (0x3e)
    .maxstack 3
    .entrypoint
    .locals init (
        [0] class ConsoleApplication2.ThreadTest/'<>c__DisplayClass0_0' 'CS$<>8__locals0'
    )

    IL_0000: newobj instance void ConsoleApplication2.ThreadTest/'<>c__DisplayClass0_0'::.ctor()
    IL_0005: stloc.0
    IL_0006: ldloc.0
    IL_0007: ldc.i4.0
    IL_0008: stfld int32 ConsoleApplication2.ThreadTest/'<>c__DisplayClass0_0'::i
    IL_000d: br.s IL_0033
    // loop start (head: IL_0033)
        IL_000f: ldloc.0
        IL_0010: ldftn instance void ConsoleApplication2.ThreadTest/'<>c__DisplayClass0_0'::'<Main>b__0'()
        IL_0016: newobj instance void [mscorlib]System.Threading.ThreadStart::.ctor(object, native int)
        IL_001b: newobj instance void [mscorlib]System.Threading.Thread::.ctor(class [mscorlib]System.Threading.ThreadStart)
        IL_0020: call instance void [mscorlib]System.Threading.Thread::Start()
        IL_0025: ldloc.0
        IL_0026: ldloc.0
        IL_0027: ldfld int32 ConsoleApplication2.ThreadTest/'<>c__DisplayClass0_0'::i
        IL_002c: ldc.i4.1
        IL_002d: add
        IL_002e: stfld int32 ConsoleApplication2.ThreadTest/'<>c__DisplayClass0_0'::i

        IL_0033: ldloc.0
        IL_0034: ldfld int32 ConsoleApplication2.ThreadTest/'<>c__DisplayClass0_0'::i
        IL_0039: ldc.i4.s 10
        IL_003b: blt.s IL_000f
    // end loop

    IL_003d: ret
} // end of method ThreadTest::Main
Run Code Online (Sandbox Code Playgroud)

为什么编译器要j在第一个场景中添加?

注意:我使用的是VS 2015 Update 3,.NET Framework 4.5.2,在Release模式下编译。

Pet*_*iho 4

因为从语义上讲,当您编写 时i++,编译器需要保留 的原始值,i以便它可以用作表达式的结果值。

编译器通过引入一个新变量来实现这一点,如果需要,新值可以保留在其中i,直到使用旧值为止。因此,旧值i仍然可以读取,直到更新的j值被复制到i. 当然,在这种情况下,在将指令的结果复制add到后立即发生j,因为实际上没有代码需要该值。但是,暂时i的价值仍然是旧的,如果需要的话可以使用。

你可能会争论:

但是,我从不使用该值。为什么编译器要保留它?为什么不直接将结果写入addi不是先存储呢j

C# 编译器不负责优化。它的主要工作是将 C# 代码翻译成 IL。事实上,我想说,这项工作的一部分是不要非常努力地优化事物,而是遵循常见的实现模式,使负责优化的 JIT 编译器上的事情变得更容易

通过不包含优化此类退化场景的逻辑,可以更轻松地确保 C# 编译器生成正确的 IL,并以可预测、更易于优化的方式生成正确的 IL。