Optimal if statements

I want to make sure that I optimize my if statements, hence some question

 

  • If you need to get a maximum of two line items, is it more efficient to use an if statement "if a > b then a else b" or to use the max formula "max(a,b)"
  • Is there any performance difference in "if x<y then a else b" vs “if y<x then b then a” (in case there is only one if statement, in case there is a nested if statement then the most common case should be put first)
  • In some languages the performance is better to have "boolean * number" instead of having an if statement "if.boolean then number else 0".
    In anaplan you cannot apply this, but we could replace the boolean as number with only 0/1's.
    Given the planual "Use conditionals to stop unnecessary calculations", it is probably still better to have the if statement?

Answers

    • If you need to get a maximum of two line items, is it more efficient to use an if statement "if a > b then a else b" or to use the max formula "max(a,b)" - max(a,b) , an inbuilt formula is always better than a conditional statement
    • Is there any performance difference in "if x<y then a else b" vs “if y<x then b then a” (in case there is only one if statement, in case there is a nested if statement then the most common case should be put first) - I dont think so, they both look same 
    • In some languages the performance is better to have "boolean * number" instead of having an if statement "if.boolean then number else 0".
      In anaplan you cannot apply this, but we could replace the boolean as number with only 0/1's.
      Given the planual "Use conditionals to stop unnecessary calculations", it is probably still better to have the if statement? - Yes right, so if you have a zero you will not do any calculation , whereas in case of 1 you will do the calculation. Hence, you will save on several calculations
  • The conditional operations IF, AND and OR all can improve performance if they allow expensive calculations to be skipped. However they impose their own penalty in the form of instruction pipeline flushes; although modern CPUs will speculatively issue instructions based on branch prediction, for trivial operations it may be more performant if refactoring is possible. In many cases the business logic embodied by the formula requires these decision points however. And let's not abandon readability - it is better to get the right answer slightly more slowly than the wrong answer slightly more quickly. The only advice I'd give in addition to nested IFs is that if a Boolean subexpression (A) is more expensive to calculate than (B) then "(B) AND (A)" is probably better than "(A) AND (B)" and likewise for OR - especially if for AND there are plenty of FALSE evaluations on the left hand side (or TRUE for OR).