Analysis of for statement nesting and statement nesting
In daily work, data processing will inevitably encounter traversal, and we may use a lot of for loops. This section discusses the nested loop Performance of the for statement and obtains the performance of the following two statements.
Statement 1
for ( i= 0; i < 1000000; i++)
{ for (j =0; j < 100; j++) { expression; }
}
Statement 2
for ( i= 0; i < 100; i++)
{ for (j =0; j < 1000000; j++) { expression; }
}
At first glance, it seems that the execution times of two nested loops are the same. is their time complexity the same? Let's analyze: Statement 1 executes the outer loop 1000000 times, the inner loop executes 1000000*100 times, and Statement 2 executes the outer loop 100 times, the inner loop is also executed for 1000000*100 times. So, since the number of executions in the inner layer is the same, is the execution of the outer layer less better? Let's write code for authentication.
Verification Code
static void Main(string[] args) { Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 1000000; i++) { for (int j = 0; j < 100; j++) { // expression; } } sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); for (int i = 0; i < 100; i++) { for (int j = 0; j < 1000000; j++) { // expression; } } sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); }
Verify
It is concluded that for nested loops of the for statement, the total number of loops is equal, and the smaller the outer loop, the better. For personal notice, take specific actions at work...
Supplementary Summary (February 3)
What we described above is a phenomenon and does not tell you the essence of things. (@ Sunday *) Sunday * tells me that "the reason is that the value assignment to int j = 0 is reduced, which will consume performance, however, this optimization is not an essential performance improvement! ", So I thought deeply. In fact, the smaller the number of times to control the outer loop, we can find that the number of I auto-increment is less, and the number of I <100 is less, and the int j = 0 value assignment in the inner loop is also less, naturally the performance is improved.
Sunday * is right:Use for to avoid creating objects and reduce the number of cycles, so as to achieve optimization;My conclusion is as follows:For nested loops of for statements, the total number of loops is equal. The smaller the outer loop, the better.Both are correct.Code is dead, people are active, and people have to control the Code flexibly. Take the code as appropriate.
Finally, I do not deny that this kind of optimization will not improve the performance much. However, if I encounter the situation mentioned in this article, I have to write the optimal code by instinct, which is also the purpose of my research.