Today LeetCode stairs write algorithm, it was found that for the circulation ++ i, when used usually in a for loop, are written like: for (int i = 0; i <10; i ++), with i ++. Today, however, when looking at the algorithm and found some for loop like this: for (int i = 0; i <10; ++ i), using ++ i.
Just saw when he was thinking the for loop i ++ and ++ i What difference does it make?
Try it yourself a bit and found them in the for loop effect is exactly the same!
First, we should all know the difference between ++ i and i ++ are: ++ i is the first execution i = i + 1 and then use the value of i, and i ++ is executed first and then i = i + 1 using the value of i;
Then we also know that the order of execution for loop as follows:
for(A;B;C)
{
D;
}
Into the loop executes A; // only enter when executed.
Execution B; // condition is true before the implementation of D, otherwise they jumped for the.
Execution D;
execute C;
go back to step 2 started
so we then see below example:
1.For (int I = 0; I <10; I ++):
for(int i = 0; i<10; i++) {
System.out.println(i);
}
Equivalent to
for(int i=0; i<10;)
{
System.out.println(i);
i++;
}
2.for (int i=0; i<10; ++i):
for(int i = 0; i<10; ++i) {
System.out.println(i);
}
Equivalent to
for(int i=0; i<10;)
{
System.out.println(i);
++i;
}
In the loop, and the role of i ++ ++ i is the same.
The information is printed: 1-10
print information also demonstrated the role that i ++ and ++ i is the same.
However, by this step we also did not know the effect is the same, but they certainly have some differences.
So I went to the time-consuming cycle also print out
the number of cycles = 100 when:,
number of cycles = 1000 time:,
number of cycles = 10000 When:,
I believe we can also see the difference, yes, that is the running time makes a difference, not much less when the cycles out, but when the number of cycles we go up then this gap is a little obvious. Then, after careful examination exploration discovery: Take store the return value before the increment in Java i ++ statement is the need for a temporary variable, while ++ i do not. This will cause the system need to apply for a period of memory space when using i ++, then the value of the game as in, do you have to go last release. So much more than a series of operating time, of course, ah, finally I suggest that you write for later in the cycle does not affect the logic in the case of multi-use ++ i, less use i ++, this, too, a certain degree of system optimization is not.