x=x+1 vs. x +=1

后端 未结 17 1106
独厮守ぢ
独厮守ぢ 2020-12-29 02:57

I\'m under the impression that these two commands result in the same end, namely incrementing X by 1 but that the latter is probably more efficient.

If this is not c

17条回答
  •  囚心锁ツ
    2020-12-29 03:16

    So many speculations! Even the conclusion with the Reflector thingy is not necessarily true because it can do optimizations while dissassembling.

    So why does none of you guys just have a look into the IL code? Have a look at the following C# programme:

    static void Main(string[] args)
    {
        int x = 2;
        int y = 3;
        x += 1;
        y = y + 1;
        Console.WriteLine(x);
        Console.WriteLine(y);
    }
    

    This code snippet compiles to:

    .method private hidebysig static void Main(string[] args) cil managed
    {
    .entrypoint
    // Code size 25 (0x19)
    .maxstack 2
    .locals init ([0] int32 x,
    [1] int32 y)
    // some commands omitted here

    IL_0004: ldloc.0
    IL_0005: ldc.i4.1
    IL_0006: add
    IL_0007: stloc.0

    IL_0008: ldloc.1
    IL_0009: ldc.i4.1
    IL_000a: add
    IL_000b: stloc.1

    // some commands omitted here
    }

    As you can see, it's in fact absolutely the same. And why is it? Because IL's purpose is to tell what to do, not how to. The optimization will be a job of the JIT compiler. Btw it's the same in VB.Net

提交回复
热议问题