mardi 10 mars 2020

Does excluding the `else` affect the performance in Python 3?

I was looking for an existing answer to this question, and while I came across this answer specifically about C#, this is a compiler-level thing, and so I'd expect Python might differ here.

Look at these two ways of terminating a function. First the one with the else:

if condition:
    return some_val
else:
    return some_other_val

Then the one without it:

if condition:
    return some_val
return some_other_val

Logically, the two do precisely the same thing, even if condition has side effects. They test condition, then return a value.

Is there a chance that Python 3 optimizes one over the other?

Aucun commentaire:

Enregistrer un commentaire