In reading "Programmer interview written book", found such a problem, the book only gives the ++i more efficient, but did not give specific explanations and explanations.
Find the following answers online:
1, from the advanced level to explain
++i is i=i+1, the value of the expression is I itself
I++ is also i=i+1, but the value of the expression is the copy before 1, which is less efficient because you want to save the copy first.
For C + + built-in types, most compilers do optimizations, so there is no difference in efficiency. However, on the custom type, it is not necessarily optimized, ++i efficiency will be higher.
2, from the bottom of the assembly to see the built-in type
int a,i=0; A=++i; The assembly code is as follows: int a,i=0;01221a4e mov dword ptr [I],0a=++i;01221a55 mov eax,dword ptr [i]01221a58 add eax,101221a5b mov dwor D ptr [i],eax01221a5e mov ecx,dword ptr [i]01221a61 mov dword ptr [A],ecxint a,i=0; a=i++; The assembly code is as follows: int a,i=0;009e1a4e mov dword ptr [I],0a=i++;009e1a55 mov eax,dword ptr [i]009e1a58 mov dword ptr [a],eax009e1 A5B mov ecx,dword ptr [i]009e1a5e add ecx,1009e1a61 mov dword ptr [I],ECX
As you can see from the assembly code above, the number of executions is the same for the built-in types, with no difference in efficiency.
3, from overloaded operators to see the custom type
Operator operator::operator++ () {++value;//Internal member variable return *this;} Operator operator::operator++ (int) {Operator Temp;temp.value=value;value++;return temp;}
As can be seen from the above code, the Post + + has an operation to save the temporary object, so the efficiency is naturally lower.
Summarize:
For C + + built-in types, the efficiency of the two is not very different;
For custom classes, ++i is more efficient.
Reference article:
Http://www.cplusplus.me/1303.html
(c + +) i++ and ++i, which are higher efficiency