How can I optimize my algorithm by replacing if-then-else statements with case statements?

90 Views Asked by At

One may consider using case rather than if-then-else statements. If there are different cases, then the code goes to the right choice. This will save time without going through everything.

If f_op is v_op then
    If o_op == f_op then
        If (o_r_type == "C" AND f_r_type == "D") OR 
           (o_r_type == "D" AND f_r_type == "C") OR 
           (o_r_type == "C" AND f_r_type == "C") then
             do nothing 
        else if o_r_type == "D" AND f_r_type == "D" then
            v_b.add(i)

     else if o_op_cat == f_op_cat then
            v_b.add(i)

How to modify above pseudocode and use case statements instead of if-then-else.

1

There are 1 best solutions below

0
trincot On

Assuming that the possible values of f_r_type and o_r_type are "C" and "D" (confirmed in comments) there are some remarks to make:

  • when if o_r_type == "D" AND f_r_type == "D" then is executed, that condition will always be found to be true: all other possibilities were already excluded by the previous if condition.

  • Related: the longer if condition (with three combination tests) tests the opposite of the next if condition, and so you could reduce code by only using that next condition.

  • The very first two if statements can be joined into one if statement.

  • As there is only one action that is or is not performed (v_b.add(i)), you should only need one if statement that combines all the conditions for it into one.

Your code would do the same if it were written like this:

if (f_op == v_op AND ((o_r_type == "D" AND f_r_type == "D") 
                       OR (o_op_cat == f_op_cat)) then
    v_b.add(i)

Here there is no gain for using a switch statement, as you really only have one case.