Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 make it exactly the same as ++i?

like image 995
Erwin Mayer Avatar asked Jul 31 '11 13:07

Erwin Mayer


2 Answers

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.

like image 94
Hans Passant Avatar answered Nov 03 '22 23:11

Hans Passant


The compiler should optimise the code whichever way you write it so I believe i = i + 1 is the same as ++i.

like image 38
Seth Avatar answered Nov 04 '22 01:11

Seth