4

This is a bit of an abstract question, I hope that's ok (if not, please let me know of a better place to ask it):

I have a bunch of boolean conditions, let's call them A, B, C, D, ....

In my code, I need to use these conditions to distinguish between several different possible scenarios. For example, I could have something like this (in pseudo code):

if ((A and B) or not (C or D)) then process case 1
if (A and (not B) and (C or D)) then process case 2
otherwise process case 3

Now, I can start to combine these if-statements to optimize the number of evaluations needed, like:

if (A) then {
    if (B) then {
        process case 1
    } else {
        if (C or D) then process case 2
                    else process case 1
    }
} else {
    if (C or D) then process case 3
                else process case 1
}

But I could equally well "short-circuit" (I'm using the term loosely) some of the evaluations differently, like:

if (C or D) then {
    if (A) then {
        if (B) then process case 1
               else process case 2
    } else {
        process case 3
    }
} else {
    process case 1
}

Let's say that there is a significant difference in the cost of evaluating these conditions, e.g. some require a database call, others are simple variable-null-checks, etc. Then, there is probably an optimal solution for how to break up the code (assuming all cases are somewhat equally likely).

For example, if the evaluation of A and B is cheap while the evaluation of C or D is expensive, the first version above is probably better on average as there is a chance that if A and B turn out true, C and D never need to get evaluated. Whereas if C and D are cheap while A or B are expensive, version two is better on average.

Is there some formal framework or other approach for figuring out this optimization?

Markus A.
  • 12,349
  • 8
  • 52
  • 116
  • Wonderful question, but if you're unsuccessful asking here, try the beta [**Computer Science** StackExchange](http://cs.stackexchange.com/) . – kjhughes Sep 19 '14 at 00:24
  • I think this question is quite analogous to Nodes in a Network. You can conceivable draw a network of paths to each of the possible cases. You can also assign costs to each of the nodes. This means that your can use networking graph theory to solve this problem? – Makoto May 19 '16 at 22:10

0 Answers0