Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How often do you worry about how many if cases will need to be processed?

If you have the following:

$var = 3; // we'll say it's set to 3 for this example
if ($var == 4) {
    // do something
} else if ($var == 5) {
    // do something
} else if ($var == 2) {
    // do something
} else if ($var == 3) {
    // do something
} else {
    // do something
}

If say 80% of the time $var is 3, do you worry about the fact that it's going through 4 if cases before finding the true case?

I'm thinking on a small site it's not a big deal, but what about when that if statement is going to run 1000s of times a second?

I'm working in PHP, but I'm thinking the language doesn't matter.

like image 644
Darryl Hein Avatar asked Nov 28 '22 02:11

Darryl Hein


1 Answers

Here's how we did it when I used to write software for radar systems. (Speed matters in radar. It's one of the few places where "real time" actually means "real" instead of "fast".)

[I'll switch to Python syntax, it's easier for me and I'm sure you can interpret it.]

if var <= 3:
    if var == 2:
        # do something
    elif var == 3:
        # do something
    else: 
        raise Exception
else:
    if var == 4:
        # do something
    elif var == 5:
        # do something
    else:
        raise Exception

Your if-statements form a tree instead of a flat list. As you add conditions to this list, you jiggle around the center of the tree. The flat sequence of n comparisons takes, on average, n/2 steps. The tree leads to a sequence of comparisons that takes log(n) comparisons.

like image 168
S.Lott Avatar answered Dec 17 '22 14:12

S.Lott