Home  >  Article  >  Backend Development  >  A brief analysis of the differences and efficiency between i++ and ++i in PHP

A brief analysis of the differences and efficiency between i++ and ++i in PHP

不言
不言Original
2018-06-04 17:29:591712browse

This article mainly introduces relevant information about the difference and efficiency between i and i in PHP. It is very good and has reference value. Friends in need can refer to it

Let’s look at the basic differences first:

i: First use the current value of i in the expression where i is located, and then add 1 to i

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

Watch some video tutorials and write i instead of i when writing a for loop. Go online. After searching, it turns out that there is an efficiency problem

i is equivalent to the following code

i += 1; 
return i;

i is equivalent to the following code

j = i; 
i += 1; 
return j;

Of course, if the compiler will optimize out these differences, then the efficiency will be almost the same.

Let me explain in detail the difference between i and i

1. The usage of i (with a= i, i =2 for example)

First add 1 to the value of i (that is, i=i 1), and then assign it to variable a (that is, a=i),

Finally The value of a is equal to 3 and the value of i is equal to 3.

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

2. Usage of i (take a=i, i=2 as an example)

First assign the i value to variable a (that is, a=i), then add 1 to the i value (that is, i=i 1),

Then the final a value is equal to 2, and the i value equal to 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. When i and i are used alone, it is equivalent to i=i 1

If assigned to a new variable, i first adds 1 to the i value, and i first assigns i to the new variable.

The above is the detailed content of A brief analysis of the differences and efficiency between i++ and ++i in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn