mercredi 22 janvier 2020

How to improve a bunch of else-if conditions that evaluate a variable inside a range among known values?

Is there any way to convert this code below into something more scalable? I've simplified it, but my real one has to check for several different values and it is asking for refactoring.

     if (x < 0) foo1();
else if (x < 3) foo2();
else if (x < 8) foo3();
else            foo4();

I've tried the following:

struct Ptr2foo {
    void (*foo_x)();
}

Ptr2foo ptr2foo_x[4] {
    foo1,
    foo2,
    foo3,
    foo4
}

ptr2foo_x[someMagicWithMy_X_AndMyKnownValues].foo_x();

Those values are known before compiling, and that amount of conditions inside a loop are killing performance.

Is this the best way to approach this issue? Any alternative solution with its explanation is highly appreciated

Aucun commentaire:

Enregistrer un commentaire