I'm having an issue with my Python code, but that's something I had already encountered in other languages and I'd like to have a general answer.
Let's say I have a loop containing many statements. One of these statements depends on a condition that does not change over the iterations. I see two ways to implement this:
for ... :
... #many statements
if conditionA :
statementA
elif conditionB :
statementB
else
statementC
or :
if conditionA :
for ... :
... #many statements
statementA
elif conditionB :
for ... :
... #many statements
statementB
else :
for ... :
... #many statements
statementC
In the first solution, the problem is that we test something at each iteration, which isn't necessary. The second solution has a better speed because it just tests the condition once and then starts the loop accordingly, which is what I want to do ; but now there is a lot of code duplication (many statements rewritten everytime...).
Is there a third way I haven't thought of that would be as efficient as the second one but without code duplication? Thanks!
EDIT :
I read on a similar topic (Optimizing a Loop vs Code Duplication) that C++ compilers already do the optimization (by transforming the first version into the second one during compilation). What about interpreted languages such as Python?