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?
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.
The compiler should optimise the code whichever way you write it so I believe i = i + 1 is the same as ++i.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With