In this section, we will see an interesting problem. We will see two code snippets. Both have two nested loops. We need to determine which one will run faster. (We will assume that the compiler does not optimize the code).
for(int i = 0; i < 10; i++){ for(int j = 0; j<100; j++){ //code } }
for(int i = 0; i < 100; i++){ for(int j = 0; j<10; j++){ //code } }
Both segments of code will run the same number of times. The code inside the two loops will be executed 10000 times in both cases. But if we look closely, we can understand that the second piece of code does more tasks than the first piece of code. In the first piece of code, the inner loop will execute 10 times. Therefore, the initialization, condition check, and increment operations will be performed 10 times. But for the second piece of code, the inner loop will execute 100 times. Therefore, the initialization, condition checking and incrementing operations will be performed 100 times. So it will take longer than the first piece of code.
The above is the detailed content of A nested loop puzzle?. For more information, please follow other related articles on the PHP Chinese website!