Which is faster? ++, += or x + 1?

后端 未结 5 1102
轮回少年
轮回少年 2020-12-10 01:41

I am using C# (This question is also valid for similar languages like C++) and I am trying to figure out the fastest and most efficient way to increment. It isn\'t just one

5条回答
  •  误落风尘
    2020-12-10 02:18

    They are same:

    static void Main(string[] args)
    {
        int a = 0;
        a++;
        a +=1;
        a = a+1;
    }
    

    The above code in ILSpy is:

    private static void Main(string[] args)
    {
        int a = 0;
        a++;
        a++;
        a++;
    }
    

    Also the IL for all these is same as well (In Release mode):

    .method private hidebysig static void  Main(string[] args) cil managed
    {
        .entrypoint
        // Code size       15 (0xf)
        .maxstack  2
        .locals init ([0] int32 a)
        IL_0000:  ldc.i4.0
        IL_0001:  stloc.0
        IL_0002:  ldloc.0
        IL_0003:  ldc.i4.1
        IL_0004:  add
        IL_0005:  stloc.0
        IL_0006:  ldloc.0
        IL_0007:  ldc.i4.1
        IL_0008:  add
        IL_0009:  stloc.0
        IL_000a:  ldloc.0
        IL_000b:  ldc.i4.1
        IL_000c:  add
        IL_000d:  stloc.0
        IL_000e:  ret
    } // end of method Program::Main
    

提交回复
热议问题