FrozzenFinger
FrozzenFinger

Reputation: 1540

Complexity of if statement inside or outside for loop

Let's compare this:

for path in filePaths :
    if(self.module!=organizer and self.module!=decoder):
        # some code with loops
    elif(self.module==decoder):
        # some code with loops

and this:

if(self.module!=organizer and self.module!=decoder):
    for path in filePaths :
        # some code with loops
elif(self.module==decoder):
    for path in filePaths :
        # some code with loops

Which one is the most efficient and why?

Upvotes: 1

Views: 171

Answers (1)

Mureinik
Mureinik

Reputation: 311228

They both have an O(n) complexity, but the latter is more efficient. Since self.module doesn't change during the execution of the loop, there's no point in checking it in each iteration.

Upvotes: 3

Related Questions