Nick N.
Nick N.

Reputation: 41

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

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.

Upvotes: 2

Views: 1660

Answers (3)

Moshe Slavin
Moshe Slavin

Reputation: 5204

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.

Upvotes: 0

AgMr
AgMr

Reputation: 96

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.

Upvotes: 0

bruno
bruno

Reputation: 32586

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

Upvotes: 1

Related Questions