Skip to content Skip to sidebar Skip to footer

Two Loops Performance Difference. Swapping Inner And Outer Loop

I had two loops (one nested in the other one) and I was wondering if there is any difference in how I nest these loops. Results of Code 1 and Code 2 are the same (100,000x4 = 4x100

Solution 1:

The difference is in the loop initialization code. The first code has to initialize the inner loop 100,000 times while the second one only does that 4 times.


Solution 2:

Analyze the code as if each operation had a cost and you will see that this makes sense.

In test code 2, you are stuck on the nested loop 100,000 times, but go to the outer loop 4 times. Instead, in test code 1, you alternate between the two.

The first test code runs more operations than the seconds.


Post a Comment for "Two Loops Performance Difference. Swapping Inner And Outer Loop"