Mitch
Mitch

Reputation: 1634

Which is more efficient? A nested if in a for loop or a separate if with a separate for loop?

So I'm trying to decide which of these is more efficient, or if there is a difference between them. The program I'm writing iterates through a for loop (python) and does some stuff, and then, depending on a flag, will write to a file.

Example A:

for element in list:
    Do stuff
    if(write_to_file):
       write to file

Vs example B:

for element in list:
    Do stuff
if(write_to_file):
    for element in list:
        write to file

In the case of A it has to check every time if it's true, but in the case of B if it is true it has to then re-do the for loop. My thought is that they're equal, but I'd like opinions of more experienced programmers

Upvotes: 2

Views: 287

Answers (2)

rbutcher
rbutcher

Reputation: 1345

Example C:

if(write_to_file):
    for element in list:
        Do stuff
        write to file
else:
    for element in list:
        Do stuff

As others have said, you will probably not be able notice the difference between any of these approaches.

Upvotes: 1

James Mills
James Mills

Reputation: 19030

Based on the Big O complexity analysis of your example(s):

for element in list:
    Do stuff
if(write_to_file):
    for element in list:
        write to file

The above is less efficient because you are iterating over list twice.

i.e: O(n) x 2

But please test yourself, use the timeit module and most importantly of all you are worrying prematurely about optimization. get it working first!

Read also: When to optimize

Upvotes: 2

Related Questions