The differences between I ++ and I in C,
I believe that the code writers are no stranger to I ++ and I, but do you fully understand these two methods? The following describes their differences. Simply put, I ++ is used first, and ++ I is used first.
1 int I = 0; 2 int y = 1; 3 y = I ++; 4 Console. writeLine ("y value: {0}", y. toString (); 5 Console. writeLine ("I value: {0}", I. toString ());
The running result of the above Code:
Next, let's look at the Code:
1 int I = 0; 2 Console. writeLine ("reference first, and then calculate, So I is still {0}", (I ++ ). toString (); 3 Console. writeLine ("the value of I in memory is {0}", I. toString (); 4 Console. writeLine ("calculate first, then reference, so the value of I is {0}", (++ I ). toString (); 5 Console. readLine ();
Run the following code:
I ++ is often used in a for loop. What is the difference between I ++ and I in a for loop? Continue to read the code:
1 var count = 0; 2 for (int I = 1; I <= 10; I ++) 3 {4 count + = 1; 5} 6 Console. writeLine ("cycles: {0}", count. toString (); 7 Console. readLine ();
Running result:
What if I ++ in the for loop is changed to ++ I? Check the Code:
1 var count = 0; 2 for (int I = 1; I <= 10; ++ I) 3 {4 count + = 1; 5} 6 Console. writeLine ("cycles: {0}", count. toString (); 7 Console. readLine ();
Running result:
It can be seen that I ++ and I have the same number of cycles for the for loop, but is there any difference in performance? Continue to read the code:
1 Stopwatch sw = Stopwatch. startNew (); 2 // string count = string. empty; 3 4 // long ticks; 5 for (int I = 1; I <= 100; I ++) 6 {7 // count = I. toString (); 8} 9 sw. stop (); 10 var elapsed = sw. elapsed; 11 // Console. writeLine ("cycles: {0}", count. toString (); 12 Console. writeLine ("Time consumed: {0}", elapsed. toString (); 13 Console. readLine ();
Running result:
Replace I ++ with ++ I. The running result is as follows:
The for loop is 100 times, and the loop does not do anything. According to the running result on the author's computer, I ++ is better than ++. Now I change the number of cycles to 10000000 (10 million) times, what is the result?
What if some transaction logic is added to the for loop? The code is changed:
1 Stopwatch sw = Stopwatch. startNew (); 2 string count = string. empty; 3 4 // long ticks; 5 for (int I = 1; I <= 100; I ++) 6 {7 count = I. toString (); 8} 9 sw. stop (); 10 var elapsed = sw. elapsed; 11 Console. writeLine ("cycles: {0}", count. toString (); 12 Console. writeLine ("Time consumed: {0}", elapsed. toString (); 13 Console. readLine ();
The result of testing the number of cycles to 100 is as follows:
I ++:
++ I is as follows:
Change the cycle count to 10 million:
I ++:
++ I is as follows:
In terms of performance, I ++ and I are not much different, basically at the same order of magnitude. I ++ is generally used in a for loop.