Analysis of the difference between i++ and ++i in PHP and _php example of efficiency

Source: Internet
Author: User

First look at the basic difference:

i++: First use the current value of I in the expression where I is, then let I add 1

++i: Let I add 1 first, and then use the new value of I in the expression where I is

See some video tutorials inside write for loop is written ++i instead of i++, Internet search for a while, the original efficiency problem

++i is equivalent to the following code

i + 1; 

i++ is equivalent to the following code

j = i; 
i + 1; 
Return J;

Of course, if the compiler will optimize these differences, then the efficiency is all the same.

To give you a detailed talk about the difference between ++i and i++

1, the use of ++i (A=++i, i=2 as an example)

First add the I value by 1 (that is, i=i+1), and then assign the variable a (that is, a=i),

The final a value is equal to 3, and the I value equals 3.

So a=++i is equivalent to i=i+1, a=i

2, the use of i++ (a=i++, i=2 as an example)

First assigns the I value to the variable a (that is, a=i), and then the I value plus 1 (that is, i=i+1),

The final a value is equal to 2, and the I value equals 3.

So a=i++ is equivalent to A=i, i=i+1

3, ++i and i++

A=++i is equivalent to i++, a=i

a=i++ is equivalent to A=i, i++

4, ++i and i++ when used alone, the equivalent of i=i+1

If you assign a new variable, ++i first adds the I value to 1, and i++ first assigns I to the new variable.

The above is a small set to introduce PHP i++ and ++i of the difference and efficiency of all the narration, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.