The original address

introduce

If you’ve written a for loop before, you’ve almost certainly used i++ to increment loop variables. But have you ever wondered why you did that?

Obviously, the end result of using I ++ is to make the variable +1, but there are many ways to do this: ++ I, I = I +1.

This article introduces ++ I and I ++ and explains why ++ I is probably better than I ++ in most cases.

i++

I++ is the method we often use in the loop, which is implemented as follows:

int j = i;
i = i + 1;
return j;
Copy the code

I ++ must return the original value of I, not the increment of I + 1, so the old version of I must be stored. This means that extra memory is required to store the value, and, in most cases, we don’t actually use the old value, just throw it away.

++i

The ++ I method is rarely used, usually by older programmers in languages such as C and C++. Its implementation is as follows:

i = i + 1;
return i;
Copy the code

Note that instead of saving the old value of I, we simply add it from +1 and return it. This dovetails with the opportunity we use in the for loop, because we rarely use the old value of I.

Matters needing attention

After learning the difference between the two operators, you may notice that since the cached value of I is never used after I ++, the compiler optimizes the operator to make the two operators equivalent.

For primitive types, such as integers, this is likely true.

However, for more complex types, such as user-defined types or iterators with a + operation overload, the compiler may not be able to safely optimize the cache operation.

So it seems that in most cases, as long as you don’t need the preceding value of the incrementing value, ++ I will be better than or equal to I ++.


Follow our official account to read more technical articles