Let $E_1, E_2, \ldots, E_n$ be boolean-valued expressions, each with an associated evaluation cost and probability of returning true
. For simplicity, assume these probabilities are independent, so that $\mathbb{P}(E_i \cap E_j) = \mathbb{P}(E_i) \, \mathbb{P}(E_j)$ for $i \ne j$.
Suppose we want to compute the expression $E_1 \mathbin{\&\&} E_2 \cdots \mathbin{\&\&} E_n$. Here $\mathbin{\&\&}$ means short-circuit evaluation, so if $E_1$ is false
then $E_2$ is not evaluated, etc. The expected cost of a short-circuit evaluation is
$$ \mathop{\mathbb{E}} \mathrm{cost}(E_i \mathbin{\&\&} E_j) = \mathrm{cost}(E_i) + \mathbb{P}(E_i) \, \mathrm{cost}(E_j) \\\\ \mathop{\mathbb{E}} \mathrm{cost}(E_i \mathbin{\&\&} E_j \mathbin{\&\&} E_k \cdots) = \mathrm{cost}(E_i) + \mathbb{P}(E_i) (\mathrm{cost}(E_j) + \mathbb{P}(E_j) (\mathrm{cost}(E_k) + \cdots)) \\\\ $$
If the expressions have no side effects then they can be freely reordered. Is there an efficient way to find the ordering with the lowest expected cost? There is a dynamic programming algorithm based on finding the min-cost ordering of every subset:
$$ \min \mathrm{cost} \{E_1, E_2, \ldots, E_n\} = \min_i [\mathrm{cost}(E_i) + \mathbb{P}(E_i)\min \mathrm{cost} \{\ldots, E_{i-1}, E_{i+1}, \ldots\}] $$
but since it computes costs for every subset it takes $O(2^n)$ time.