(c + +) i++ and ++i, which are higher efficiency

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.