2

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 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.