Single loop containing multiple if-statements or multiple if-statements with loops inside?

Viewed 801

Is it recommended to create multiple if statements and nest loops inside of them or create one loop and nest multiple if statements inside of that? I am wondering in terms of memory, time, and other factors I may have overlooked.

Here is some pseudocode:

if a: for i in range(500): do x if b: for i in range(500): do y

versus

for i in range(500): if y: do x if z: do p

In other words, when is the best time to do the if-statement. Inside a few nested loops or before any of the loops?

I am also wondering this because it may be more efficient to do one if statement at the beginning for a check then do the loops nested in this if statement. However, this might result in lots of repeated code.

3 Answers

The first way is the best for the performances, you do the test one time rather than at each turn

Of course I suppose there is no side effect making the two solutions different

In some situations, you won't be able to check the condition before the loop, but if you can this is the better solution because a condition is checked one time instead of every loop iteration.

It really depends what you are iterating through and what you need to check for!

If you need to check each iteration in both cases a and b you should go with option 2.

But if it's either a or b just go with option 1.

Related