Wednesday, May 4, 2016

Nested loops : Best practices

Consider the following two examples:

Click on the image to enlarge


I have 2 questions for you now.

1) Will both the loops take the same time to execute?
2) Which is a better programming approach?

75% of the programmers would say, there will not be any changes, both the loops will execute identical. Who knows you may also think that way, I bet you are gonna change that opinion by end of this article. Or at least know why we follow something as a ‘best practice’

Let us analyze both the situations. In both cases there are 3 executable statements viz two for loops and one Print statement.

Assumption : Let us assume that every executable statement takes 1 second to execute 

Let us analyze the first situation:

Let us go line by line,


Line 1 (For i=1 to 100) : This will be executed for 100 positive conditions and 1 negative condition. Total 101 executions, there by taking 101 seconds 
Execution time for line 1 = 101 seconds

Line 2 (For j=1 to 5) : This statement will be executed for 5 positive conditions and 1 negative condition. Total 6 executions for every positive conditions of line 1, which will be 100. So making it 100x6 executions which will be 600.
Execution time for line 2 = 600

Line 3 (Print “Hello”) : For statement will be executed for every positive condition of Line 1 and Line 2. Therefore, 100x5 times it will be executed.
Execution time for line 3 = 500

Therefore the total execution time for first situation = 101 + 600 + 500 = 1201 seconds

Let us now analyse the second situation:

Let us again go line by line,


Line 1 (For j=1 to 5) : This will be executed for 5 positive conditions and 1 negative condition. Total 6 executions, there by taking 6 seconds 
Execution time for line 1 = 6 seconds

Line 2 (For i=1 to 100) : This statement will be executed for 100 positive conditions and 1 negative condition. Total 101 executions for every positive conditions of line 1, which will be 5. So making it 5x101 executions which will be 505.
Execution time for line 2 = 505

Line 3 (Print “Hello”) : For statement will be executed for every positive condition of Line 1 and Line 2. Therefore, 5x100 times it will be executed.
Execution time for line 3 = 500

Here the total execution time for 2nd situation = 6 + 505 + 500 = 1011 seconds.

Did you ever realize this??? Yes, Always remember...
We should have the lesser iteration loop in the outer and more iterations loop inner.



No comments:

Post a Comment