Is there any performance difference with ++i vs i += 1 in C#?

后端 未结 5 703
半阙折子戏
半阙折子戏 2021-01-19 12:42

i += a should be equivalent to i = i + a. In the case where a == 1, this is supposedly less efficient as ++i as it involves more accesses to memory; or will the compiler mak

5条回答
  •  甜味超标
    2021-01-19 13:16

    It is easy to answer: the C# compiler translates C# source code to IL opcodes. There is no dedicated IL opcode that performs the equivalent of the ++ operator. Which is easy to see if you look at the generated IL with the ildasm.exe tool. This sample C# snippet:

            int ix = 0;
            ix++;
            ix = ix + 1;
    

    Generates:

      IL_0000:  ldc.i4.0               // load 0
      IL_0001:  stloc.0                // ix = 0
    
      IL_0002:  ldloc.0                // load ix
      IL_0003:  ldc.i4.1               // load 1
      IL_0004:  add                    // ix + 1
      IL_0005:  stloc.0                // ix = ix + 1
    
      IL_0006:  ldloc.0                // load ix
      IL_0007:  ldc.i4.1               // load 1
      IL_0008:  add                    // ix + 1
      IL_0009:  stloc.0                // ix = ix + 1
    

    It generates the exact same code. Nothing the jitter can do but generate machine code that is equally fast.

    The pre/post increment operator is syntax sugar in C#, use it wherever it makes your code more legible. Or perhaps more relevant: avoid it where it makes it less legible. They do have a knack for letting you create expressions that have too many side-effects.

提交回复
热议问题