weidler weidler - 6 months ago 26
Python Question

Does the Order of Conditions affect Performance?

Does it matter how I order the conditions in Python in respect to the speed of the script? In SQL e.g. it does not as the "Interpreter" assumes which condition ordering would be the fastest.

In Python, as far as I know, the order of conditions will be taken as given by the interpreter. So as an example, if I chain or-conditions, is it better to order the conditions by assumed time they will consume because maybe the interpreter stops even looking for the other conditions when the first one doesn't apply anyway?


Yes, the order of conditions matters. They are evaluated left-to-right unless you change that by using parentheses, for example.

And yes, conditions are only evaluated if the outcome of the expression isn't already clear. For example, in

if 1==0 and foo**10000 > 2:

Python will return False immediately and not even attempt to calculate foo**10000.