Does the Order of Conditions affect Performance?
<p>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. </p>

<p>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?</p>

<p>Boolean operators in Python are <a href="https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not" rel="nofollow">short-circuiting</a> - as soon as the result of an expression is clear, evaluation stops. This plays an important role in Python's late-binding.</p>

<p>For example, this is a common check:</p>

<pre><code>def do(condition_check=None):
    if condition_check is not None and condition_check():
        # do stuff
</code></pre>

<p>Python is in general very conservative about premature optimizations. If there is any chance that something might break, Python will not try it.</p>

<p>If you want to check Interpreter optimizations, try the <code>dis</code> module. It shows the instructions actually being run by the Python core. For example, Python will resolve constant expressions (<code>10**10</code> => <code>10000000000</code>) and back out of an <code>and</code> early (<code>JUMP_IF_FALSE_OR_POP</code>).</p>

<pre><code>dis.dis('1==0 and 10**10 &gt; 2')
  1           0 LOAD_CONST               0 (1)
              3 LOAD_CONST               1 (0)
              6 COMPARE_OP               2 (==)
              9 JUMP_IF_FALSE_OR_POP    21
             12 LOAD_CONST               4 (10000000000)
             15 LOAD_CONST               3 (2)
             18 COMPARE_OP               4 (&gt;)
        &gt;&gt;   21 RETURN_VALUE
</code></pre>

<p>Note that not even pypy does any further optimization on this code!</p>

python performance condition