I am getting this by following this approach
First for x++:-
It stores the value of x first then make copy of that number and then increment it when occurs same variable again so 3 clock cycle are there one for store the other copy of the number then increment that number.
So 3 is performace unit for the post increment
Now for ++x
It directly increment the value in the variable and store it so only 2 cycle 1 for increment and other for store the value.
Now for x = x + 1
It first take an value in variable then perform addition then assign to the variable at left side so it too take 3 unit for performance.
So it is similar as post increment.
If you are using x+=1 then take value in x and 1 to it only 2 step and it will equal to the pre increment.
4rontender in C++ at the back-end when source code is converted into assembly level then the code is in its optimized form as in compiler, compiler has important layers, lexical analyzer, syntax analyzer, semantics analyzer, code optimizer. In code optimizer all this source code statement is converted in most optimized code by using 3 address variables code and different parsing algorithm.
But in the front level pre increment is faster as it takes no time to increment value.
x+=1 is used as it is quick too read by compiler from left to right as variable x is only need to match in symbol table of memory one time so it is faster.
And in x=x+1 the variable x needs to match twice so it is take much time to execute.
Thus += is used in general.
High level language compilers are smart enough to optimise the codes now.
I tried to run following C# tests on LINQPad 5, they all generate the same assembly codes.
Assembly code output:
IL_0002: stloc.0 // x
IL_0003: ldloc.0 // x
IL_0006: stloc.0 // x
Calviղ's snippet even gives me different results the more often I run it!
4rontender It is Intermediate Language, IL of c#, the lower level of it. The IL has opcodes that manipulate the stack.
Here I've added the comments of the operation of these opcodes:
IL_0001: ldc.i4.1 // push the value of 1 onto stack, x
IL_0002: stloc.0 // pop the value from the top of the stack
IL_0003: ldloc.0 // load the local variable onto stack
IL_0004: ldc.i4.1 // push value 1 (increment value, i) onto stack
IL_0005: add // add 2 values (x+i) and add the result onto stack
IL_0006: stloc.0 // pop the current value from stack
Schindlabua yes, it generates different results when we run more..
The speed of the rest are closely the same.
Anyway you're right, we don't actually concerns too much about the speed different between increment operator, it's not significant if compare to other operations.